11694503	11694227	Read write object to JSON	System.Web.Script.Serialization.JavaScriptSerializer oSerializer = \nnew System.Web.Script.Serialization.JavaScriptSerializer();\nstring sJSON = oSerializer.Serialize(YOUR CLASS HERE);	0
19853771	19853696	How to use ProgressBar inside nested foreach loop?	private void CopyWithProgress(string[] filenames)\n    {\n        // Display the ProgressBar control.\n        pBar1.Visible = true;\n        // Set Minimum to 1 to represent the first file being copied.\n        pBar1.Minimum = 1;\n        // Set Maximum to the total number of files to copy.\n        pBar1.Maximum = filenames.Length;\n        // Set the initial value of the ProgressBar.\n        pBar1.Value = 1;\n        // Set the Step property to a value of 1 to represent each file being copied.\n        pBar1.Step = 1;\n\n        // Loop through all files to copy. \n        for (int x = 1; x <= filenames.Length; x++)\n        {\n            // Copy the file and increment the ProgressBar if successful. \n            if(CopyFile(filenames[x-1]) == true)\n            {\n                // Perform the increment on the ProgressBar.\n                pBar1.PerformStep();\n            }\n        }\n    }	0
1593256	1593235	Linq to XML -Dictionary conversion	var dictionary = instructors.Elements("instructor")\n                            .Select((element, index) => new { element, index })\n                            .ToDictionary(x => x.index + 1,\n                                          x => x.element.Value);	0
5224216	5224169	C# Service calls Console Application that doesn't close	var p = Process.Start( ... );\n\n// ...\n\nif (!p.WaitForExit(5000)) { // wait 5 seconds\n  p.Kill();\n}	0
21432391	21432356	How to get all values as a single string from NameValueCollection?	string allValues = string.Join(System.Environment.NewLine, valueCollection.AllKeys.Select(key => valueCollection[key]));	0
33188547	33188466	C# String array	string sInvite = @"\n\n*********************************************\n\n                   " + sGuest + @"\n        is invited to the wedding of:\n        " + sBride + @" and " + sGroom + @"\n    On Saturday 17 July 2016 at 2:00pm\n\n*********************************************";\n\nConsole.WriteLine(sInvite);	0
26635505	26635348	Remove new line character from C# String	var lines = str.Split('\n')\n                .Where(s => !string.IsNullOrWhiteSpace(s));\n\nstr = string.Join("\n", lines);	0
28553455	28552567	Web API 2: how to return JSON with camelCased property names, on objects and their sub-objects	protected void Application_Start()\n{\n    HttpConfiguration config = GlobalConfiguration.Configuration;\n    config.Formatters.JsonFormatter.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver()\n    config.Formatters.JsonFormatter.UseDataContractJsonSerializer = false;\n}	0
13339354	13315076	Adding rows to XtraGrid using interfaces	gridView1.OptionsBehavior.AllowAddRows = DevExpress.Utils.DefaultBoolean.True;\n    gridView1.OptionsBehavior.AllowDeleteRows = DevExpress.Utils.DefaultBoolean.True;\n    gridView1.OptionsView.NewItemRowPosition = NewItemRowPosition.Bottom;\n    //...\n    var bindingList = new BindingList<IPerson>(){\n        new Person(){ Name="John", Age=23 },\n        new Person(){ Name="Mary", Age=21 },\n    };\n    bindingList.AddingNew += bindingList_AddingNew; //  <<--\n    bindingList.AllowNew = true;\n    gridControl1.DataSource = bindingList;\n}\n\nvoid bindingList_AddingNew(object sender, AddingNewEventArgs e) {\n    e.NewObject = new Person(); //   <<-- these lines did the trick\n}\n//...\npublic interface IPerson {\n    string Name { get; set; }\n    int Age { get; set; }\n}\nclass Person : IPerson {\n    public string Name { get; set; }\n    public int Age { get; set; }\n}	0
28759317	28758002	Can't save PdfPage as a BitmapImage to disk	WriteableBitmap wb = new WriteableBitmap(1,1);\nawait wb.SetSourceAsync(str);	0
8660085	8658065	Creating Datagridview at runtime	private void button1_Click(object sender, EventArgs e)\n{\n\n    SqlConnection con = new SqlConnection(@"Data Source=SUBASH-LAPTOP\COBRA;Initial Catalog=Test;Integrated Security=True");\n\n    SqlCommand Command = con.CreateCommand();\n\n    SqlDataAdapter dp = new SqlDataAdapter("Select * From orders where date_purchased <= @varDate", con);\n    dp.SelectCommand.Parameters.AddWithValue("@varDate", dateTimePicker1.Value);\n    DataSet ds = new DataSet();\n    dp.Fill(ds);\n    DataGridView d1 = new DataGridView();\n    d1.DataSource = ds;\n    d1.DataMember = ds.Tables[0].TableName;\n    this.Controls.Add(d1);\n\n}	0
5506329	5505873	Button to show panel	pnlSettings.Location = new Point(0, 0);\n    pnlSettings.Size = this.ClientSize;\n    this.Controls.Add(pnlSettings);	0
9208972	9208873	Closing a running program from commandline	var currentProcess = System.Diagnostics.Process.GetCurrentProcess();\n        var matchingProcesses = System.Diagnostics.Process.GetProcesses().Where(x => x.Id != currentProcess.Id && x.ProcessName == currentProcess.ProcessName);\n        foreach (var process in matchingProcesses) {\n            process.Kill();\n        }	0
11792578	11792244	How to trim a string and store residue in a array?	var source = "sometext\n\t\t\t\t00:00\n\t\t\t\t05:32\n\t\t\t\t...."\n var result = source.Split(new []{"\n\t\t\t\t"}, StringSplitOptions.None);	0
29344945	29344413	Pivot data in two nested List<T> with Linq	var result = employees.SelectMany(x => x.WorkDays, (employeeObj, workDays) => \n                                                   new { employeeObj, workDays })\n                      .GroupBy(x => x.workDays.Date)\n                      .Select(x => new\n                             {\n                                Date = x.Key,\n                                NameAndHours = x.Select(z => \n                                    new { \n                                            Name = z.employeeObj.Name, \n                                            Hours = z.workDays.Hours \n                                        })\n                             }).ToList();	0
5002038	5001685	OLE date (number) to date (string)	DateTime.FromOADate([double])	0
11674499	11674302	how can I download all the linked mp3s from a web page?	HtmlDocument doc = new HtmlDocument();\n doc.Load("file.htm");\n\n List<string> mp3Links = new List<string();\n foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])\n {\n    if(link != null)\n    {\n      if(link["href"].EndsWith(".mp3"))\n      {\n        mp3Links.Add(link["href"].Value);\n      }\n    }\n }	0
2978651	2978597	How do I launch .net windows forms application with no visible windows?	Application.Run()	0
33371005	33370312	How to prevent to change other column values into table while updating single column using Entity Framework?	var context = new DbContext();\n\n// Load entity via whatever Id parameter you have.\nvar entityToUpdate = context.Set<Type>().FirstOrDefault(x => x.Id == idToUpdate);\n\nif(entityToUpdate != null)\n{\n    entityToUpdate.Value1 = newValue1;\n    entityToUpdate.Value2 = newValue2;\n\n    context.SaveChanges();\n}	0
13904348	13903901	Retrieving specific chracters based on their Unicode code pont	var charSet = new HashSet<char>("abcde\x015f" + Regex.Unescape("\u0066"));\n//or var charSet = new HashSet<char>(new[] { 'a', 'b', 'c', 'd', 'e', '?', 'f'});\n//or var charSet = new HashSet<char>(new[] { '\x0061', '\x0062', '\x0063', '\x0064', '\x0065', '\x015F', '\x0066'});\n//or var charSet = new HashSet<char>(Regex.Unescape("\u0061\u0062\u0063\u0064\u0065\u015F\u0066"));\n//or var charSet = new HashSet<char>("\x0061\x0062\x0063\x0064\x0065\x015F\x0066");\n\nstring input = "abc  def? aaa xyz";\n\nvar words =  input.Split()\n                .Where(s => !String.IsNullOrWhiteSpace(s))\n                .Where(s => s.All(c => charSet.Contains(c)))\n                .ToList();	0
1957771	1957763	Clearing a TextBox in ASP.NET	textbox.text = string.Empty;	0
17459127	17459022	Regex grab and rewrite string between two other keywords	modify = Regex.Replace(modify, @"FEW0*(\d+)0", "few clouds at $1,000.");	0
18266197	18265676	Printing WPF Document	PrinterSettings settings = new PrinterSettings();//System.Drawing.Printing.PrinterSettings\n  PrintDocument printDoc = new PrintDocument();\n\n  settings.Copies = Copiesnumber; //put your number of copies\n\n  printDoc.PrinterSettings = settings;\n\n  PageSettings MyPage = new PageSettings(settings);\n\n  printDoc.DefaultPageSettings = MyPage;	0
2730647	2728869	Bulkinsert from CSV into db (C#) -> max number of rows in a web application?	CREATE PROCEDURE [dbo].[usp_ExecuteBulkInsertTask]  \n(  \n @dataFile   VARCHAR(255),  \n @bulkInsertFormatFile  VARCHAR(255),  \n @tableName  VARCHAR(255)  \n)  \nAS \nBEGIN\nBEGIN TRY\nDECLARE @SQL Varchar(4000)  \n\n SET @SQL = 'BULK INSERT ' + @tableName  + ' FROM ''' + @dataFile + ''' WITH (formatfile=''' + @bulkInsertFormatFile + ''', FIRSTROW=2)'  \n EXEC sp_sqlexec  @SQL\nEND TRY\nBEGIN CATCH\n --error handling\nEND CATCH\nEND	0
8480639	8480534	Embeding Images in an Email Using Outlook Interop	System.Net.Mail	0
6895670	6894654	LinqDataSource Where Parameter	Where="ConfiguredCarId.Contains(@ConfiguredCarId)"	0
9426044	9425934	How to make a query in PostgreSQL with the text in Upper()	NpgsqlDataAdapter da = new NpgsqlDataAdapter("Select NombreMarca From Marca Where UPPER(NombreMarca) ='"+cbMarca.Text.ToUpper()+"'", conn);	0
15885562	15885522	date month not displaying correctly	string date = string.Format("{0:MMddyyHHmmss}", DateTime.Now);	0
27408645	27408517	can't get control using FindControl in GridView	var dropDown  = GridView1.Rows[GridView1.EditIndex].FindControl("ddlprioridade") as DropDownList;	0
31884302	31884234	How do I prevent Long / Int64 ToString() converting to Exponential Format?	long num = 1234567890123456789;\nSystem.Diagnostics.Debug.WriteLine("Str=" + num.ToString("0"));	0
3901111	3900978	Accessing non-static DAL methods	public void Save(Article article)\n{\n    ArticleDAL art = new ArticleDAL();\n    art.Save(article);\n}	0
10296607	10296452	How to Compare two IEnumerable Collections using LINQ	var result = from ap in AvailablePacks  \n             join rp in RecommendedPacks \n               on ap.PackID equals rp.PackID\n               select new {\n                  PackQuantity = ap.Quantity\n               };	0
16386567	16386534	RegEx Replace Matching Sequence and Stripping Whitespaces	var t = str.split(':');\nvar result = '<Entry Name="'+t[1]+'" Code="'+t[0].trim().replace(/ /g,'')+'"/>';	0
27257306	27257262	Create a method taking alternative parameter variable types	/// <summary>\n/// Writes a string followed by a newline to the console\n/// </summary>\n/// <param name="s">The value to write</param>\npublic void WriteLine(string s)\n{\n    //Do something with a string\n}\n\n/// <summary>\n/// Writes the string representation of an object followed by a newline to the console\n/// </summary>\n/// <param name="o">The value to write</param>\npublic void WriteLine(object o)\n{\n    //Do something with an object\n}	0
17910101	17909651	C# Get cursor line in RichTextBox	private void richTextBox1_SelectionChanged(object sender, EventArgs e)\n{\n    int index = richTextBox1.SelectionStart;\n    int line = richTextBox1.GetLineFromCharIndex(index);\n    label1.Text = "cursor at line " + line.ToString();\n}	0
28753435	28591263	Update Sql Table from datagridview c#	private void update_sql(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyChar == (char)13)\n    {\n        fletera_facturasTableAdapter.Update(indarDataSet2.fletera_facturas);\n        **indarDataSet2.fletera_facturas.AcceptChanges();**\n    }\n}	0
32192200	32192144	C# create DataView from DataView	var filtered = dt.AsEnumerable()\n                 .Where(r => r.Field<int>("ID") < 1000);\n\n\nDataView dv1 = filtered.AsDataView();\n\nDataView dv2 = filtered.Where(r => r.Field<string>("Salary") > 50000)\n                       .AsDataView();	0
4944521	4944435	How can I get the name of my Windows Service at runtime?	String source = this.ServiceName;	0
26454634	26454557	if statement with datatables	DataRow[] foundRows = rightFileDT.Select(expression);\nif (foundRows.Length == 0)\n{\n    matchedFileDataRow["File_Match"] = "False";\n}\nelse\n{\n    matchedFileDataRow["File_Match"] = "True";\n}\nmatchedFileDataRow["Left_File_Name"] = leftFileMatch;\nmatchedFileDT.Rows.Add(matchedFileDataRow);	0
4012904	4010743	is there a way to add a bookmark that is different than the text in the pdf document	style.ParagraphFormat.OutlineLevel = OutlineLevel.BodyText;	0
10158399	10158369	WP7 for loop to limit number of items added to listbox	public void jsonHome_GetDataCompleted(object snder, DownloadStringCompletedEventArgs e)\n{\n    NewReleasesCharts homeData = JsonConvert.DeserializeObject<NewReleasesCharts>(e.Result);\n\n    const int limit = 4;\n\n    this.listRelease.ItemsSource = homeData.results.featuredReleases.Take(limit);\n}	0
12387319	12387269	Close all forms in a control in Windows Forms	foreach(Form form in pnlMain.Controls.OfType<Form>().ToArray())	0
13739398	13739293	How I get the right Data from my Column with Linq	String.Format("{0:dd.MM.yyyy}", dataTable.Rows[0]["TIMEFROM"]);\nString.Format("{0:dd.MM.yyyy}", dataTable.Rows[0]["TIMETO"]);	0
25149051	25148282	Rewriting a SQL with LINQ	var innerInnerQuery = from g in GROUPS\n                      where NPI == "roupnpi" \n                          && TAXID == "grouptin"\n                          && ADDRESSTYPE_RTK == "_REI0PVM65"\n                      select g.GROUP_K;\nvar innerQuery = from ga in GROUPADDRESS\n                 where innerInnerQuery.Contains(ga.GROUP_K)\n                 select ga.ADDRESS_K;\nvar query = from a in ADDRESSES\n            where ZIPCODE == "66210"\n                && innerQuery.Contains(a.ADDRESS_K)\n            select a;	0
24527826	24527717	How to maintain a object list to remember these objects 's state change?	var route = listOfRouteObj.SingleOrDefault(route => route.RouteID.Equals("1"));\nif(route != null)\n   route.Priority = 1000;	0
19884844	19884721	C# - Displaying character count without counting spaces?	private void userTextBox_TextChanged(object sender, EventArgs e)\n{\n    string userInput = userTextBox.Text;\n    userInput = userInput.Trim();\n    string[] wordCount = userInput.Split(null);\n\n    int charCount = 0;\n    foreach (var word in wordCount)\n        charCount += word.Length;\n\n    wordCountOutput.Text = wordCount.Length.ToString();\n    charCountOutput.Text = charCount.ToString();\n}	0
10290798	10290741	How to sort dictionary by DateTime value	var dateTimesDescending = myDic.Values.OrderByDescending(d => d);	0
7824740	7822659	LINQ-to-SQL - Group By Week in Date object	int firstDayOfWeek = (int)DayOfWeek.Monday;\nvar q = \n    from u in TblUsers\n    let date = u.CreateDate.Value\n    let num = date.DayOfYear - 1\n    let num2 = ((int)date.DayOfWeek) - (num % 7)\n    let num3 = ((num2 - firstDayOfWeek) + 14) % 7\n    let week = (((num + num3) / 7) + 1)\n    group u by week into g\n    select new \n    {\n        Week = g.Key,\n        Count = g.Count ()\n    };	0
14267120	14267082	Regex - Removing a number after one parameter	string s = Regex.Replace( \n    "ID:300,Order:1,Number:30.99,Other:null",\n    @"(?<=Number:).*?(?=,|$)",\n    m => "*" );	0
4918614	4918207	how to use imageMagick with C#	string arguments = string.Format(@"-density 300 {0}.pdf {1}.png", intputFileName, outputFileName");\nvar startInfo = new ProcessStartInfo {\n    Arguments = arguments,\n    Filename = @"C:\path\to\imagick\convert.exe"\n};\nProcess.Start(startInfo).WaitForExit();	0
12384585	12384012	BusyIndicator using MVVM	public class MainWindowViewModel : ViewModelBase\n   {\n    public ViewModel1 ViewModel1 { get; set; }\n    public ViewModel2 ViewModel2 { get; set; }\n    public ViewModel3 Model3 { get; set; }\n\n    public MainWindowViewModel()\n    {\n        ViewModel1 = new ViewModel1();\n        ViewModel2 = new ViewModel2();\n        ViewModel3 = new ViewModel3();\n        ViewModel1.PropertyChanged += (s,e) => \n        {\n           if(e.PropertyName == "IsBusy") \n           { \n              // set the MainWindowViewModel.IsBusy property here\n              // for example:\n              IsBusy = ViewModel1.IsBusy;\n           }\n         }\n    //IsBusy = true; - its working\n   }\n}	0
12289457	12289102	Choosing a random entry from a JSON string	Random rnd = new Random(); //Create this random class only once.\n\nJArray obj = (JArray)JsonConvert.DeserializeObject(json);\ndynamic item = obj[rnd.Next(0, obj.Count)];\nConsole.WriteLine(item.title);	0
4856447	4856403	Installing a windows service programatically	ServiceConfiguration.ServiceName	0
414271	414267	C#: Where do you call your own save method after pressing OK on a Settings Dialog for your program?	// clicked OK, should I call SaveSettings() here?	0
7796940	7476875	Opting into IE8-mode zooming in a browser control with DOCHOSTUIFLAG_DPI_AWARE	[HKEY_CURRENT_USER\Software\Microsoft\Internet Explorer\Zoom]\n"ZoomDisabled"=dword:00000001\n"ResetTextSizeOnStartup"=dword:00000001	0
3294516	3294251	Building SOAP message with XMLDocument VB.NET	Dim soapHeader As XmlElement = _xmlRequest.CreateElement("soap", "Header", "http://schemas.xmlsoap.org/soap/envelope/")\nDim soapBody As XmlElement = _xmlRequest.CreateElement("soap", "Body", "http://schemas.xmlsoap.org/soap/envelope/")	0
27615822	27615776	Passing data between user controls in wpf	// Button_Click event\nWindow window = new Window\n{\n     Title = "Window2",\n     Content = new UserDataControl2("My Data");\n};\n\n\n// User Control class.\nstring _info;\n\npublic UserDataControl2(string info)\n{\n   _info = info.\n};	0
14450156	14450116	Is it possible to reuse array variable in c#?	contactAddress = new []{"xxx","yyy"};	0
29887715	29887446	How do I remove blank lines from text File in c#.net	File.Replace	0
12404347	12386437	can you return implicit type from a method?	object GetSomething()\n{\n    var x = new { a = "b", i = 1 };\n    return x;\n}	0
11236741	11236154	Adding a vertical scrollbar to a panel if drawn area is too large	AutoScroll=true	0
16761298	16761196	Need a vb equivalent on a declaration of list of tasks	Dim tasks =\n    { Task.Delay(3000).ContinueWith(Function(_) 3),\n      Task.Delay(1000).ContinueWith(Function(_) 1),\n      Task.Delay(2000).ContinueWith(Function(_) 2),\n      Task.Delay(5000).ContinueWith(Function(_) 5),\n      Task.Delay(4000).ContinueWith(Function(_) 4),\n    }	0
7759884	7759018	How to write: insert into table ALL except X, if statement	public bool BatchInsert(string table, IEnumerable<string> values)\n    {\n        var sql = new StringBuilder();\n        sql.Append("INSERT INTO " + table + " VALUES(");\n\n        var newValues = values.Where(x => !x.StartsWith("LIFT")).Select(x => string.Format("'{0}'", x.Replace("'", "''")));\n        sql.Append(string.Join("","", newValues.ToArray()));\n        sql.Append(")");\n\n        using (var comm = new SqlCommand(statement, connectionPCICUSTOM))\n        {\n            try\n            {\n                comm.Connection.Open();\n                comm.ExecuteNonQuery();\n            }\n            catch (Exception e)\n            {\n                KaplanFTP.errorMsg = "Database error: " + e.Message;\n            }\n            finally\n            {\n                comm.Connection.Close();\n            }\n        }\n        return true;\n    }	0
16562208	16562175	How can I sort ObservableCollection?	Persons = new ObservableCollection<Person>(from i in Persons orderby i.Age select i);	0
13077121	12985990	set page layout for report viewer in visual studio 2010	System.Drawing.Printing.PageSettings pg=new System.Drawing.Printing.PageSettings();\n pg.Margins.Top = 0;\n pg.Margins.Bottom = 0;\n pg.Margins.Left = 0;\n pg.Margins.Right = 0;\n System.Drawing.Printing.PaperSize size = new PaperSize();\n size.RawKind = (int)PaperKind.A5;\n pg.PaperSize = size;\n reportViewer1.SetPageSettings(pg);\n this.reportViewer1.RefreshReport();	0
11647453	11647286	Drag and Drop one control to another control in winform	void listBox1_DragDrop(object sender, DragEventArgs e)\n{\n  e.Effect = DragDropEffects.Copy;\n}\n\nvoid listBox1_DragEnter(object sender, DragEventArgs e)\n{\n  e.Effect = DragDropEffects.Copy;\n}	0
5129229	5128628	Strange results from win32_NetworkAdapterConfiguration	ManagementObjectSearcher intquery1 = new ManagementObjectSearcher("SELECT * FROM Win32_NetworkAdapterConfiguration  WHERE Description ='" + comboBox1.Items[comboBox1.SelectedIndex].ToString() + "'");\nManagementObjectCollection queryCollection1 = intquery1.Get();\nqueryCollection1 = intquery1.Get();\n\nforeach (ManagementObject mo1 in queryCollection1)\n{\n   string[] addresses = (string[])mo1["IPAddress"];\n   string[] gateways = (string[])mo1["DefaultIPGateway"];\n   string[] subnets = (string[])mo1["IPSubnet"];\n\n   if (addresses != null)\n   {\n       listBox1.Items.Clear();\n       foreach (string ip in addresses)\n       {\n           listBox1.Items.Add(ip);\n       }\n   }\n   if (gateways != null)\n   {\n       foreach (string gateway in gateways)\n       {\n          TxtGateway.Text = (gateway);\n       }\n   }\n   if (subnets != null)\n   {\n       foreach (string subnet in subnets)\n       {\n           richTextBox1.Text = (subnet);\n       }\n   }\n}	0
13955612	13955247	how can I remove with specific tags from html	string text = @"<div><span class=""help"">This is text.</span>Hello, this is text.      </div>\n                <div>I have a question.<span class=""help"">Hi</span></div>";\nHtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(text);\nvar nodes = doc.DocumentNode.SelectNodes("//span[@class='help']");\nforeach( HtmlNode node in nodes)\n{\n   node.Remove();\n} \nString result = doc.DocumentNode.InnerHtml;	0
4143192	4143098	how to set login control to compare the credentials stored in  web.config?	if (FormsAuthentication.Authenticate(username, password))\n {\n  //you can set cookie\n  FormsAuthentication.SetAuthCookie(username, false);\n  //redirect when user is authenticated\n  FormsAuthentication.RedirectFromLoginPage(username, false);\n }\n else\n {\n  //invalid login\n }	0
11364264	11353392	Json Deserialization of form Dictionary<string, Dictionary<string, string>>	string json = @"[{""Key"" : ""Microsoft"", ""Value"":[{""Key"":""Publisher"",""Value"":""abc""},{""Key"":""UninstallString"",""Value"":""c:\temp""}]}]";\n\nvar list = JsonConvert.DeserializeObject< List<KeyValuePair<string,List<KeyValuePair<string, string>>>> >(json);\n\nvar dict= list.ToDictionary(\n         x => x.Key, \n         x => x.Value.ToDictionary(y=>y.Key,y=>y.Value));	0
13056222	13056107	Remove Hexa without char in each line	TextBox2.Text = System.Text.RegularExpressions.Regex.Replace(\n                    TextBox1.Text, \n                    @"^.{49}", \n                    "", \n                    RegexOptions.Multiline );	0
20422218	20421318	Marshall Struct containing unions with arrays	[StructLayout(LayoutKind.Explicit, Pack = 1)]\npublic unsafe struct PNIO_ADDR\n{\n    [FieldOffset(0)]\n    public PNIO_IO_TYPE AddrType;\n\n    [FieldOffset(4)]\n    public PNIO_IO_TYPE IODataType;\n\n    // container, size:20bytes\n    [FieldOffset(8)]\n    //[MarshalAs(UnmanagedType.ByValArray, SizeConst = 5)]\n    public fixed uint Reserved[5];\n\n    [FieldOffset(8)]\n    [MarshalAs(UnmanagedType.U4)]\n    public uint Addr;\n}	0
4599670	4599624	C# VSTO Outlook 2007: How to show contact by EntryID	string entryid = ...\n\nvar outlookApp = new Outlook.Application();\nvar outlookNS = outlookApp.Session;\nvar fldContacts = outlookNS.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderContacts);\nvar contact = outlookNS.GetItemFromID(entryid, fldContacts.StoreID);	0
20204462	20204454	Enum value extraction	Enum.GetValues(typeof(View)).Cast<View>().Take(6);	0
23079097	23078881	remove html input tag from string using C#	var temp = "The accounting equation asset = capital + liabilities, which of the             following is true. Ram has started business with 5,50,000 and has purchased goods worth 1,50,000 on credit <input type='radio' id='op1' name='q2option' value='1' /> a) 7,00,000 = 5,50,000 + 1,50,000 <input type='radio' id='op2' name='q2option' value='2' />b)7,00,000 = 6,50,000 + 50,000 <input type='radio' id='op3' name='q2option' value='3' /> c) 5,50,000 = 7,00,000 - 1,50,000 <input type='radio' id='op3' name='q2option' value='4' /> d)5,50,000 = 5,00,000 + 50,000";\n\nvar regInput = new Regex("(.*?)(\\<input[^\\>]*\\>)(.*?)");\n\nvar result =regInput.Replace(temp,"$1$3");	0
24857902	24857880	How can I order data returned in an anonymous type?	.OrderBy( z => z.AnswerId)	0
8019341	8019314	Search a record in a list without scanning all of records	List<T>.BinarySearch	0
6925134	6914691	Getting IWin32Window interface of a MMC snap-in	SnapIn.Console.ShowDialog	0
15465449	15465320	Calculate time to launch from arrival time and travel time	using System;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Console.Title = "Datetime checker";\n            Console.Write("Enter the date and time to launch from: ");\n            DateTime time1 = DateTime.Parse(Console.ReadLine());\n            Console.WriteLine();\n            Console.Write("Enter the time to take off: ");\n            TimeSpan time2 = TimeSpan.Parse(Console.ReadLine());\n            DateTime launch = time1.Subtract(time2);\n            Console.WriteLine("The launch time is: {0}", launch.ToString());\n            Console.ReadLine();\n        }\n    }\n}	0
7011473	7011423	C# - use symbols from other class without qualifying with classname	class MathCalculations\n{\n    private Func<double, double, double> min = Math.Min;\n    private Func<double, double, double> max = Math.Max;\n    private Func<double, double> sin = Math.Sin;\n    private Func<double, double> tanh = Math.Tanh;\n\n    void DoCalculations()\n    {\n        var r = min(max(sin(3), sin(5)), tanh(40));\n    }\n}	0
2290303	2290262	Search for a string in Enum and return the Enum	enum Colors {Red, Green, Blue}\n\n// your code:\nColors color = (Colors)System.Enum.Parse(typeof(Colors), "Green");	0
5053891	5053837	C# equivalent of Event Objects in c++ , winapi	bool bCreated;\nvar ev = new EventWaitHandle(true, EventResetMode.AutoReset, @"Global\myGlobalEvent", out bCreated);	0
2620328	2620311	Breaking down currency in c#	for (numberOfBills[0] = 0; totalAmount >= 20; numberOfBills[0]++)\n    {\n        totalAmount = totalAmount - 20;\n    }\n    for (numberOfBills[1] = 0; totalAmount >= 10; numberOfBills[1]++)\n    {\n        totalAmount = totalAmount - 10;\n    }\n    for (numberOfBills[2] = 0; totalAmount >= 5; numberOfBills[2]++)\n    {\n        totalAmount = totalAmount - 5;\n    }\n    for (numberOfBills[3] = 0; totalAmount > 0; numberOfBills[3]++)\n    {\n        totalAmount = totalAmount - 1;\n    }	0
7830944	7830908	How to use BinaryReader in loop so I can display chunks of information in correct format?	FileStream readStream = new FileStream(FILE_NAME, FileMode.Open, FileAccess.Read);\nBinaryReader read = new BinaryReader(readStream);\n\nwhile (read.PeekChar() != -1)\n{\n    book.readDataFrom(read);\n    book.display();\n}	0
2269818	2269800	How to get string type for nullable types	if (item.PropertyType.IsGenericType) {\n    if (item.PropertyType.GetGenericType() == typeof(Nullable<>)) {\n        var valueType = item.PropertyType.GetGenericArguments()[0];\n    }\n}	0
2117082	2117050	How to get a Type object from Type's name?	Type type2 = Type.GetType(type.AssemblyQualifiedName);	0
18068831	18068732	How to get to a node in a namespaced xml file?	var xDoc = XDocument.Load(fname);\nXNamespace ns = "http://soap.sforce.com/2006/04/metadata";\n\nvar folder = xDoc.Root.Element(ns + "rffolder").Value;	0
20825269	20825086	Using JSON and HTTP Request in C#	public static String getJsonData(String webServiceName,String parameter)\n{  \ntry  \n{\n    String urlFinal=SERVICE_URI+"/"+webServiceName+"?parameter=";\n    HttpPost postMethod = new HttpPost(urlFinal.trim()+""+URLEncoder.encode(parameter,"UTF-8"));\n\n    postMethod.setHeader("Accept", "application/json");\n    postMethod.setHeader("Content-type", "application/json");\n\n    HttpClient hc = new DefaultHttpClient();\n\n    HttpResponse response = hc.execute(postMethod);\n    Log.i("response", ""+response.toString());\n    HttpEntity entity = response.getEntity();\n    String responseText = EntityUtils.toString(entity);\n\n    string=responseText;\n    Log.i("Output", ""+responseText);\n      }\n      catch (Exception e) {\n        // TODO: handle exception\n    }\n\nreturn string;\n}	0
8124098	8123757	How to add tooltip for Checkboxlist  for each item in asp.net	protected void Page_PreRender(object sender, EventArgs e)\n{\n    foreach (ListItem item in ckl_EditRole.Items)\n    {\n        item.Attributes["title"] = GetRoleTooltip(item.Value);\n    }\n}\n\nprivate static string GetRoleTooltip(string p)\n{\n    // here is your code to get appropriate tooltip message depending on role\n}	0
24499562	24499176	Nested gridview get outer gridview row index on inner gridview footer button click	//Button Row    //GridView      //Parent row\nvar parentRow = (GridViewRow)sender.NamingContainer.NamingContainer.NamingContainer;\nvar index = parentRow.RowIndex;	0
334291	334256	How do I add a custom XmlDeclaration with XmlDocument/XmlDeclaration?	XmlDocument doc = new XmlDocument();\nXmlDeclaration declaration = doc.CreateXmlDeclaration("1.0", "ISO-8859-1", null);\ndoc.AppendChild(declaration);\nXmlProcessingInstruction pi = doc.CreateProcessingInstruction("MyCustomNameHere", "attribute1=\"val1\" attribute2=\"val2\"");\ndoc.AppendChild(pi);	0
24087145	24086553	Find row of an item template control in gridview	protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)\n{\n  DropDownList ddl = (DropDownList) sender;\n  GridViewRow row = (GridViewRow) ddl.NamingContainer;\n  int rowIndex = row.RowIndex;\n}	0
1488781	1488706	Set property Nullable<> by reflection	var propertyInfo = typeof(Foo).GetProperty("Bar");\nobject convertedValue = null;\ntry \n{ \n    convertedValue = System.Convert.ChangeType("1256", \n        Nullable.GetUnderlyingType(propertyInfo.PropertyType));\n} \ncatch (InvalidCastException)\n{\n    // the input string could not be converted to the target type - abort\n    return;\n}\npropertyInfo.SetValue(fooInstance, convertedValue, null);	0
23105297	23105171	WPF datagrid is not displaying result in one row?	var item = new IPMAC();\nforeach (Match match in matches)\n{\n      Console.WriteLine("Hardware Address : {0}", match.Groups[1].Value);\n      item.mac = match.Groups[1].Value;\n}\n\n\nforeach (Match match in matchesIP)\n{\n      Console.WriteLine("IP Address : {0}", match.Groups[1].Value);\n      item.ip = match.Groups[1].Value;\n}\nipmac.Add(item);	0
9630575	9630557	How to bind a IEnumerable<string> to a ListBox?	{Binding}	0
9080784	9080336	Domain Driven Design: access a configured value from an Entity without using a Service Locator	public MyClass\n{    \n    private readonly IAuthorizationService _authorizationService;\n\n    public MyClass(IAuthorizationService authorizationService) \n    {\n        _authorizationService = authorizationService;\n    }\n\n    void MyMethod()\n    {\n        if(_authorizationService.HasCurrentUserCompletedSecurity()) ....\n    }    \n}	0
27856897	27855828	Get Process Handle of Windows Explorer	SHDocVw.ShellWindows shellWindows = new SHDocVw.ShellWindows();\n\n        string filename;\n        ArrayList windows = new ArrayList();\n\n        foreach (SHDocVw.InternetExplorer ie in shellWindows)\n        {\n            filename = Path.GetFileNameWithoutExtension(ie.FullName).ToLower();\n            if (filename.Equals("explorer"))\n            {\n                //do something with the handle here\n                MessageBox.Show(ie.HWND.ToString()); \n            }\n        }	0
19332665	19332109	How can I get value of textbox or dropdownlist and send to database in ASP.NET MVC4	[HttpPost]\npublic ActionResult YourActionMethod(FormCollection Collection)\n{\n        string Country = string.Empty;\n\n        if (Collection["txtCountry"] != null)\n            Country = Collection["txtCountry"].ToString();\n//Else you can assign the values to your model object.\n        return View();\n}	0
20827436	20827350	Process communication	p.StartInfo.RedirectStandardInput = true;	0
2221962	2221881	Code Analysis on a Code Generator Generated File - How to Suppress Warnings?	FxCopCmd.exe /file:MyAssembly.dll /out:AnalysisResults.xml /ignoregeneratedcode	0
444507	443378	Return String from a webmethod instead of a dataset.	[WebMethod]\n    public String GetPONumber(string Database)\n    {   \n        //Create Object ready for Value\n        object po = "";\n\n        //Set Connection\n        SqlConnection Connection = new SqlConnection(GetConnString(Database));\n\n        //Open Connection\n        Connection.Open();\n\n        //Set Query to string\n        string Query = @" SQL QUERY GOES HERE!!!! ";\n\n        //Run Query\n        SqlCommand Command = new SqlCommand(Query, Connection);\n\n        //Set Value from Query\n        try\n        {\n            po = Command.ExecuteScalar();\n        }\n        catch\n        {\n            //Error\n        }\n\n        //Clean up sql\n        Command.Dispose();\n        Command = null;\n\n\n        //Clean up connection\n        Connection.Close();\n        Connection.Dispose();\n        Connection = null;\n\n        //Return Value\n        return po.ToString();\n    }	0
19346082	19345920	How can i get a fixed position in a window with XNA?	SpriteSortMode.BackToFront	0
5522264	5522232	How to lock a file with C#?	FileStream s2 = new FileStream(name, FileMode.Open, FileAccess.Read, FileShare.None);	0
24120755	24118146	How to show a form with focused appearance but not focused?	protected override void WndProc(ref Message m) {\n        if (m.Msg == 0x86) m.WParam = (IntPtr)1;\n        base.WndProc(ref m);\n    }	0
3039858	3024561	Fluent Nhibernate mapping related items	HasManyToMany(x => x.RelatedTo)\n                .Table("RelatedItems")\n                .ParentKeyColumn("ItemId")\n                .ChildKeyColumn("RelatedItemId");\n\nHasManyToMany(x => x.RelatedToMe)\n                .Table("RelatedItems")\n                .ChildKeyColumn("ItemId")\n                .ParentKeyColumn("RelatedItemId");	0
9210493	9210428	How to convert class into Dictionary<string,string>?	someObject.GetType()\n     .GetProperties(BindingFlags.Instance | BindingFlags.Public)\n          .ToDictionary(prop => prop.Name, prop => prop.GetValue(someObject, null))	0
18966490	18966105	Selecting Consecutive String Entries with LINQ to Entities	AsEnumerable()	0
419176	419122	logging user logins for the purpose of reporting that the client is exceeding number of licenses	SessionId  EventType  .... your session data here ... SessionCount   \n1.     1         Login         ................                 1\n2.     2         Login         ................                 2\n3.     3         Login         ................                 3\n4.     1         Logout        ................                 2\n5.     4         Login         ................                 3\n6.     4         Logout        ................                 2\n7.     2         Logout        ................                 1\n8.     3         Logout        ................                 0\n9.     5         Login         ................                 1\n10.    6         Login         ................                 2	0
3833846	3833718	WebBrowser Copy Image to Clipboard	IHTMLDocument2 doc = (IHTMLDocument2) webBrowser1.Document.DomDocument;\nIHTMLControlRange imgRange = (IHTMLControlRange) ((HTMLBody) doc.body).createControlRange();\n\nforeach (IHTMLImgElement img in doc.images)\n{\n  imgRange.add((IHTMLControlElement) img);\n\n  imgRange.execCommand("Copy", false, null);\n\n  using (Bitmap bmp = (Bitmap) Clipboard.GetDataObject().GetData(DataFormats.Bitmap))\n  {\n    bmp.Save(@"C:\"+img.nameProp);\n  }\n}	0
3536509	3536479	How to check if an object is null	using System;\n\n[Serializable]  //the missing piece\npublic class RegisterFormData\n{\n    public string username { get; set; }\n    public string pass1 { get; set; }\n    public string pass2 { get; set; }\n    public string email { get; set; }\n    public string firstname { get; set; }\n    public string lastname { get; set; }\n}	0
12157788	12157684	split string by char C#	string input = "[l=9;f=0;r=5;p=2];[l=9;f=0;r=6;p=2]";\nvar list = Regex.Matches(input, @"\[.+?\]")\n            .Cast<Match>()\n            .Select(m => m.Value)\n            .ToList();	0
1526863	1526809	How do I appease FxCop when a property getter/setter needs LinkDemand?	public int Foo\n{\n   [SecurityPermission(...)]\n   get\n   {\n      return GetFoo();\n   }\n\n   [SecurityPermission(...)]\n   set\n   {\n      SetFoo(value);\n   }\n}	0
27525927	27507002	String builder with fixed length of characters and spaces in right side in C'	StringBuilder _header = new StringBuilder();\n_header.Append(string.Format("{0,4}", "0128"));\n_header.Append(string.Format("{0,-20}", name ));	0
22459541	22458968	RegEx to extract a sub level from url	string testCase = "http://test/mediacenter/Photo Gallery/Conf 1/1.jpg";\n    string urlBase = "http://test/mediacenter/Photo Gallery/";\n\n    if(!testCase.StartsWith(urlBase))\n    {\n        throw new Exception("URL supplied doesn't belong to base URL.");\n    }\n\n    Uri uriTestCase = new Uri(testCase);\n    Uri uriBase = new Uri(urlBase);\n\n    if(uriTestCase.Segments.Length > uriBase.Segments.Length)\n    {\n        System.Console.Out.WriteLine(uriTestCase.Segments[uriBase.Segments.Length]);\n    }\n    else\n    {\n        Console.Out.WriteLine("No child segment...");\n    }	0
18479912	18461681	How to parse JSON?	var jo = JObject.Parse(json);\n        var data = (JObject)jo["Job"];\n        foreach (var item in data)\n        {\n            JToken token = JToken.Parse(item.Value.ToString());\n\n            Console.WriteLine(token.Value<String>("id"));\n        }	0
2311383	2311368	Validate date on the format "yyMMdd" in ASP.NET	DateTime.ParseExact("091223", "yyMMdd", CultureInfo.InvariantCulture);	0
24086040	24085456	How do I cast a variable to the same type of a dynamic variable?	static private List<T> AmplifyPCM<T>(ICollection<T> samples, ushort bitDepth, float volumePercent)\n{\n    var highestSample = 0;\n    var temp = new List<T>();\n\n    foreach (var sample in samples)\n    {\n        if ((dynamic)sample < 0)\n        {\n            temp.Add(-(dynamic)sample);\n        }\n        else\n        {\n            temp.Add(sample);\n        }\n    }\n\n    foreach (var sample in temp)\n    {\n        if ((dynamic)sample > highestSample)\n        {\n            highestSample = (dynamic)sample;\n        }\n    }\n\n    temp = null;\n\n    var ratio = (volumePercent * (Math.Pow(2, bitDepth) / 2)) / highestSample;\n    var newSamples = new List<T>();\n\n    foreach (var sample in samples)\n    {\n        newSamples.Add((dynamic)(T)sample * ratio);\n    }\n\n    return newSamples;\n}	0
12368168	9411948	Transactional operation with SaveChanges and ExecuteStoreCommand	using (var dataContext = new ContextEntities())\n{\n   dataContext.Connection.Open();\n   var trx = dataContext.Connection.BeginTransaction();\n\n   var sql = "DELETE TestTable WHERE SomeCondition";\n   dataContext.ExecuteStoreCommand(sql);\n\n   var list = CreateMyListOfObjects(); // this could throw an exception\n   foreach (var obj in list)\n      dataContext.TestTable.AddObject(obj);\n   dataContext.SaveChanges(); // this could throw an exception\n\n   trx.Commit();\n}	0
3934658	3934624	convert unix file	TextReader.ReadLine	0
29498039	29490929	How to dynamically map inner type using AutoMapper	[Test]\n    public void CustomMapping()\n    {\n        //arrange\n        Mapper.CreateMap<Source, Destination>()\n            .ForMember(d=>d.Value, opt=>opt.ResolveUsing(ResolveValue));\n        Mapper.CreateMap<SourceDataType, DestinationDataType>();\n\n        var source = new Source { Value = new SourceDataType() };\n\n        //act\n        var destination = Mapper.Map<Source, Destination>(source);\n\n        //assert\n        destination.Value.Should().Be.OfType<DestinationDataType>();\n    }\n\n    private object ResolveValue(ResolutionResult result)\n    {\n        var source = result.Context.SourceValue as Source;\n\n        if (result.Context.IsSourceValueNull || source == null || !(source.Value is SourceDataType))\n        {\n            return null;\n        }\n        var sourceValue = source.Value as SourceDataType;\n\n        return result.Context.Engine.Map<DestinationDataType>(sourceValue);\n    }	0
28600589	28600240	Strange behavior in Entity Framework with a list	var product = products.FirstOrDefault(p => p.Id == menuItem.ProductId);\nvar orderItem = new OrderItem\n{\n    ProductId = product.Id,\n    Quantity = 1,\n    UnitPrice = product.Price,\n    ListValue = 1 * product.Price,\n    //Product = product don't do this\n};	0
3993071	3993058	C# Regex help getting multiple values	Match sendMessage = Regex.Match(message,\n    @"\[message:(?<userpin>[A-Z1-9]{5})\](?<message>.+)");\n\nstring pin = sendMessage.Groups["userpin"].Value;\nstring message = sendMessage.Groups["message"].Value;	0
3948118	3944210	How to display the ouput window from an add-in?	public void Exec(string commandName, vsCommandExecOption executeOption, ref object varIn, ref object varOut, ref bool handled)\n{\n    handled = false;\n    if(executeOption == vsCommandExecOption.vsCommandExecOptionDoDefault)\n    {\n        if(commandName == "AddinTest.Connect.AddinTest")\n        {\n            // Find the output window.\n            Window outputWindow = _applicationObject.Windows.Item(Constants.vsWindowKindOutput);\n            // Show the window. (You might want to make sure outputWindow is not null here...)\n            outputWindow.Visible = true;\n\n            handled = true;\n            return;\n        }\n    }\n}	0
2225211	1621915	Get Controls collections from aspx that contains 2 calls for same ascx	protected void btn1_Click(object sender, EventArgs e)\n{\n    foreach (Control cont in tag1.Controls)\n    {\n        lbl1.Text += cont.ClientID + " ";\n    }\n\n    foreach (Control cont in tag2.Controls)\n    {\n        lbl2.Text += cont.ClientID + " ";\n    }\n}	0
15067408	15039730	How to reset RadAsyncUpload after submission in the code behind?	ScriptManager.RegisterStartupScript(this, this.GetType(), "clearUpload", String.Format("$find('{0}').deleteAllFileInputs()", rada_attach.ClientID), true);	0
20961647	20961536	Xml Deserialization - Element with attributes and a value	[XmlText]\npublic string PriceValueString { get; set; }	0
9511127	1406806	export gridview data	string attachment = "attachment; filename=Export.xls";\n\n    Response.ClearContent();\n\n    Response.AddHeader("content-disposition", attachment);\n\n    Response.ContentType = "application/ms-excel";\n\n    StringWriter sw = new StringWriter();\n\n    HtmlTextWriter htw = new HtmlTextWriter(sw);\n\n    // Create a form to contain the grid\n\n    HtmlForm frm = new HtmlForm();\n\n   gv.Parent.Controls.Add(frm);\n\n    frm.Attributes["runat"] = "server";\n\n    frm.Controls.Add(gv);\n\n    frm.RenderControl(htw);\n\n\n\n    //GridView1.RenderControl(htw);\n\n    Response.Write(sw.ToString());\n\n    Response.End();	0
17213730	17213660	C# Increment Numeric String	public class Program\n{\n    static void Main(string[] args)\n    {\n        Console.WriteLine(Counter.SerialString);\n        Counter.Serial++;\n        Console.WriteLine(Counter.SerialString);\n        Console.ReadKey();\n    }\n\n    public class Counter\n    {\n        public static int Serial;\n\n        public static string SerialString\n        {\n            get\n            {\n                return Serial.ToString("000");\n            }\n        }\n    }\n}	0
1745995	1745990	Practical use of interface events	public interface ISerialPortWatcher\n{\n    event EventHandler<ReceivedDataEventArgs> ReceivedData;\n    event EventHandler StartedListening;\n    event EventHandler StoppedListening;\n\n    SerialPortSettings PortOptions { set; }\n\n    bool Listening { get; set; }\n    void Stop();\n    void Start();\n}\n\npublic class ReceivedDataEventArgs : EventArgs\n{\n    public ReceivedDataEventArgs(string data)\n    {\n        Data = data;\n    }\n    public string Data { get; private set; }\n}	0
5286496	5283259	Datagridview Winforms Add or Delete Rows in Edit Mode with Collection Binding	var list = new List<ProductLine>(5);\n        list.Add(new ProductLine { Amount = list.Count });\n        list.Add(new ProductLine { Amount = list.Count });\n        list.Add(new ProductLine { Amount = list.Count });\n        list.Add(new ProductLine { Amount = list.Count });\n        list.Add(new ProductLine { Amount = list.Count });\n\n        var bs = new BindingSource {DataSource = list };\n        dataGridView1.DataSource = bs;	0
11775266	11775203	I want to access the each cell of the datatable. How?	int numberOfColumns = dt.Columns.Count;\n\n// go through each row\nforeach (DataRow dr in dt.Rows)\n{\n    // go through each column in the row\n    for (int i = 0; i < numberOfColumns; i++)\n    {\n        // access cell as set or get\n        // dr[i] = "something";\n        // string something = Convert.ToString(dr[i]);\n    }\n}	0
3332160	3332115	How to upload multiple files to FTP Server without blocking in C#?	ThreadPool.QueueUserWorkItem(FtpUpload, "path/to/file1.txt");\nThreadPool.QueueUserWorkItem(FtpUpload, "path/to/file2.txt");\nThreadPool.QueueUserWorkItem(FtpUpload, "path/to/file3.txt");\n\n...\n\nprivate static void FtpUpload(object state) {\n    var filePath = (string)state;\n    ... upload here ...\n}	0
4257176	4257114	Case insensitive search in a text file	foreach (String Row in File.ReadLines("Test.txt"))\n{\n    if (Row.IndexOf("asd", StringComparison.InvariantCultureIgnoreCase) != -1)\n    {\n        // The row contains the string.\n    }\n}	0
1891562	1891544	How can I implement the piano key frequency function in C#?	double F = 440.0 * Math.Pow(2.0, (n-49.0)/12.0);	0
25862253	25862135	How to use StringComparison.CurrentCultureIgnoreCase while checking array items in another string	private string getAccount(string dummyAccount)\n{\n    //e.g dummyAccount="resturant business";\n    string Account = string.Empty;\n\n    if ((new string[] { "abc", "Xyz", "MD" }).Any(a => dummyAccount.IndexOf(a, StringComparison.InvariantCultureIgnoreCase)>=0))\n    {\n        Account = "Unknown account";\n    }\n    else if ((new string[] { "shop", "hotel", "Resturant", "Business" }).Any(a => dummyAccount.IndexOf(a, StringComparison.InvariantCultureIgnoreCase) >= 0))\n    {\n        Account = "Business";\n    }\n    else if ((new string[] { "school", "college" }).Any(a => dummyAccount.IndexOf(a, StringComparison.InvariantCultureIgnoreCase) >= 0))\n    {\n        Account = "University";\n    }\n    return dummyAccount;\n}	0
7069498	7069474	Passing data to a web from from a aspx.cs file in ASP.NET	keywordSearch.Value = keywords;	0
1181828	1181796	How to return a paged list from a property of a Domain Object using NHibernate and a Repository Pattern	public IEnumerable<Post> GetPosts(object threadID, int pageSize, int index, out totalPosts) \n{\n    var results = session\n        .CreateMultiCriteria()\n        .Add(GetCriteria(threadID)\n             .SetFirstResult((index - 1) * pageSize)\n             .SetMaxResults(pageSize)\n        )\n        .Add(GetCriteria(threadID)\n             .SetProjection(Projections.RowCount())\n        )\n        .List();\n\n    var counts = (IList)results[1];\n    totalPosts = (int)counts[0];\n    return ((IList)results[0]).Cast<Post>();\n}\n\nprivate DetachedCriteria GetCriteria(object threadID)\n{\n    return DetachedCriteria\n        .For<Post>()\n        .Add(Expression.Eq("Thread.Id", threadID));\n}	0
420836	420825	How to properly lock a value type?	int valueType;\nobject valueTypeLock = new object();\n\nvoid Foo()\n{\n    lock (valueTypeLock)\n    {\n        valueType = 0;\n    }\n}	0
15566741	15566670	PartialView to string	public static string RenderPartialToString(string controlName, object viewData)\n    {\n        ViewPage viewPage = new ViewPage() { ViewContext = new ViewContext() };\n\n        viewPage.ViewData = new ViewDataDictionary(viewData);\n        viewPage.Controls.Add(viewPage.LoadControl(controlName));\n\n        StringBuilder sb = new StringBuilder();\n        using (StringWriter sw = new StringWriter(sb))\n        {\n            using (HtmlTextWriter tw = new HtmlTextWriter(sw))\n            {\n                viewPage.RenderControl(tw);\n            }\n        }\n\n        return sb.ToString();\n    }\nstring content = RenderPartialToString("myView", myModel);	0
1751333	1749549	Using Silverlight MVVM with Prism/Unity, and need to detect when view is closed	public IApplicationEvents\n{\n     void OnClose();\n}	0
14083822	14083714	Initialization of variables: Directly or in the constructor?	using System;\n\nclass Base\n{\n    public Base()\n    {\n        Console.WriteLine(ToString());\n    }\n}\n\nclass Derived : Base\n{\n    private int x = 5;\n    private int y;\n\n    public Derived()\n    {\n        y = 5;\n    }\n\n    public override string ToString()\n    {\n        return string.Format("x={0}, y={1}", x, y);\n    }\n}\n\nclass Test\n{\n    static void Main()\n    {\n        // Prints x=5, y=0\n        new Derived();\n    }\n}	0
24106704	24106639	C# Remove Part of a String with only knowledge of start and end of the part	string input = @"File Name=""Unstuck20140608124131432.txt"" Path=""Unstuck20140608124131432.txt"" Status=""Passed"" Duration=""0.44""";\nvar output = Regex.Replace(input, @"Path=\"".+?\""", "");	0
22466580	22465655	C# day of week date ranges repetition pattern	private List<DateTime> GetDayofWeekDateOcurrences(DateTime start, DateTime end, int everyNthWeek, List<DayOfWeek> dw)\n{\n    int numberOfDays = end.Subtract(start).Days + 1;\n\n    var dates = Enumerable.Range(0, numberOfDays)\n        .GroupBy(i => i / 7 % everyNthWeek)\n        .Where(g => g.Key == 0)\n        .SelectMany(g => g.Select(i => start.AddDays(i))\n                          .Where(d => dw.Contains(d.DayOfWeek)))\n        .ToList();\n\n    return dates;\n}	0
19772228	19771932	Back-up my /Data folder in my c# project	System.IO.File.Copy(oldPathAndName, newPathAndName);	0
1256559	1249364	How do I get the text string of Gtk.TreeSelection selected item?	Console.WriteLine (model.GetValue (iter, 0);	0
5704685	5703934	Connecting to a database through a webservice	DataClasses1DataContext dc = new DataClasses1Datacontext();\n\nvar q = from table in dc.SomeTable\nselect table;	0
2009340	2009327	Does deleting from a LINQ DB also delete records in other tables that have a foreign key association?	on delete cascade	0
2510232	2510013	GDI+: Set all pixels to given color while retaining existing alpha value	0  0  0  0  0\n  0  0  0  0  0\n  0  0  0  0  0 \n  0  0  0  1  0 \n  R  G  B  0  1	0
13995349	13995308	Case Sensitive Dictionary Keys	Dictionary<string, string> myDict = new Dictionary<string, string>();\nmyDict.Add("A", "value1");\nmyDict.Add("a", "value2");	0
8749417	8749398	How can I add elements from one collection that do not exist in a second collection to a third collection?	List<string> results = input.Except(compareTo).ToList();	0
8219867	8219757	Small program to recover lost data	mount -o offset=32256 /dev/sda /mnt/my_hd	0
4227993	4123029	Issue with WPF Chart inside ListBox	var rand = new Random();\n  DataContext = new { PsychrometricLogs =\n    from i in Enumerable.Range(0, 5)\n    select new\n    {\n      Logs =\n        from j in Enumerable.Range(0, 10)\n        select new\n        {\n          TimeStamp = rand.Next(10),\n          Temparature = (decimal)rand.Next(100),\n          RelativeHumidity = (decimal)rand.Next(100),\n          GrainsPerPound = (decimal)rand.Next(10),\n          GrainsDepression = (decimal)rand.Next(10),\n        }\n    }};	0
4494478	4494402	Truncating a byte array vs. substringing the Encoded string coming out of SHA-256	public override void InputBuffer_ProcessInputRow(InputBufferBuffer Row) {\n\n    byte[] hashedData = CreateSha256Hash(Row.HashString);\n\n    Row.HashValue = Convert.ToBase64String(hashedData, 0, 12);\n\n}	0
7001857	7001752	Reading XML using C#	string fileFormat = string.Empty;\n\n\nXmlDocument xDoc = new XmlDocument();\nxDoc.Load(fileName);\n\nXmlNodeList auxFilesList = xDoc.GetElementsByTagName("AuxFiles");\nfor (int i = 0; i < auxFilesList.Count; i++)\n{\n   XmlNode item = classList.Item(i);\n   if (item.Attributes["AttachmentType"].Value == "csv")\n   {\n      fileFormat = item.Attributes["FileFormat"].Value;\n   }\n}	0
7388347	7388328	Determine FilePath to Resource in C#	var result = Path.GetFullPath("file.csv");\n// result == @"C:\Users\...Studio 2010\Projects\MyProject\bin\Debug\file.csv";	0
24125678	24113774	Exposing items in a ListBox through an Interface in MVP	public List<string> Permission\n    {\n        get { return lstGivenPermissions.Items.Cast<string>().ToList(); } //\n        set { lstGivenPermissions.DataSource = value; }\n    }	0
1005275	1005264	Escape text for HTML	using System.Web;\n\nvar encoded = HttpUtility.HtmlEncode(unencoded);	0
32809475	32809289	how to cast doubles from char array	var v = new byte[8];\nv[7] = 0x3F;\nv[6] = 0x34;\nv[5] = 0x00;\ndouble total = BitConverter.ToDouble(v, 0);\nConsole.WriteLine(total.ToString("0.0000000000000"));	0
11668066	11668013	How to fill a dataset with metadata even if the select query return no rows	UserTablesDataAdapter.FillSchema(UserTablesDataSet, SchemaType.Mapped);	0
25571126	25570943	Algorithm to always get oldest array index based on position of newest	| N |   |   |   |   |   |   |   // newBlockIndex at 0, adding, newBlockIndex becomes 1\n | X | N |   |   |   |   |   |   // newBlockIndex at 1, adding, newBlockIndex becomes 2\n | X | X | N |   |   |   |   |   // newBlockIndex at 2, adding, newBlockIndex becomes 3\n |   | X | N |   |   |   |   |   // newBlockIndex at 3, removing, no item before index 0, we delete it\n |   | X | X | N |   |   |   |   // newBlockIndex at 3, adding, newBlockIndex becomes 4\n...	0
819249	819216	How to load a new user control without opening a new window in WPF?	Shell parentShell = Window.GetWindow(this) as Shell;	0
22735238	22735112	accessing Isolated Storage data in a different page	private void PhoneApplicationPage_Loaded_1(object sender, RoutedEventArgs e)\n    {\n    if (IsolatedStorageSettings.ApplicationSettings.Contains("profile"))\n       {\n         Player player =(Player)IsolatedStorageSettings.ApplicationSettings["profile"];         \n        HelloName.Text ="Hello"+ player.FirstName;\n       }      \n    }	0
31696018	31695901	How can i use FileSystemWatcher to watch for file size changes?	SystemA: Writes file theRealFile.txt\nSystemA: Writes file theRealFile.rdy (0byte)\nSystemB: Watches for .rdy files and then reads theRealFile.txt	0
12825490	12824945	How to force a C# class to have a constant value in it?	class myClass{\n   public readonly int Value1;\n   public readonly string Value2;\n   public myClass(int value1, string value2){\n         Value1 = value1;\n         Value2 = value2;\n   }\n}	0
33214039	33213169	NULL pointer is returned by asking for the hostID of a door	doorFI.get_Parameter(BuiltInParameter.HOST_ID_PARAM).AsElementId();	0
12514072	12513247	Panel with fixed size	SuspendLayout();\n\nWidth = someFixedWidth;\nHeight = someFixedHeight;\n\npanel.Size = new Size(panelWidth, panelHeight);\n\npanel.Location = new Point( ClientSize.Width / 2 - panelWidth / 2, ClientSize.Height / 2 - panelHeight / 2);\npanel.Anchor = AnchorStyles.None;\npanel.Dock = DockStyle.None;\n\nResumeLayout();	0
18431220	18426970	Convert DataTable to Generic List	public List<List<string >> retListTable()\n    {\n\n        DataTable dt = new DataTable();\n        adap.Fill(dt);\n\n        List<List<string>> lstTable = new List<List<string>>();\n\n        foreach (DataRow row in dt.Rows)\n        {\n            List<string> lstRow = new List<string>();\n            foreach (var item in row.ItemArray )\n            {\n                lstRow.Add(item.ToString().Replace("\r\n", string.Empty));\n            }\n            lstTable.Add(lstRow );\n        }\n\n        return lstTable ;\n\n    }	0
8532628	8532592	How to share a variable between C# and JavaScript?	protected void Page_Load(object sender, EventArgs e)\n    {\n        if (Page.IsPostBack)\n        {\n            currentTab = Int32.Parse(HiddenTabValue.Value);\n        }\n\n    }	0
10281539	10281521	C# - Automatically generating keys in a SortedList	List<T>	0
18834340	18834315	After I modify Settings at runtime and I close my application these settings are gone	Properties.Settings.Default.Save();	0
2721952	2721845	lock shared data using c#	public class Example\n{\n  private BlockingQueue<Task> m_Queue = new BlockingQueue<Task>();\n\n  public void StartExample()\n  {\n    Thread producer = new Thread(() => Producer());\n    Thread consumer = new Thread(() => Consumer());\n    producer.Start();\n    consumer.Start();\n    producer.Join();\n    consumer.Join();\n  }\n\n  private void Producer()\n  {\n    for (int i = 0; i < 10; i++)\n    {\n      m_Queue.Enqueue(new Task());\n    }\n  }\n\n  private void Consumer()\n  {\n    while (true)\n    {\n      Task task = m_Queue.Dequeue();\n    }\n  }\n}	0
20759385	20759213	Access a property of IEnumerable	foreach (object item in ItemsSource)\n{\n    var property = item.GetType().GetProperty(DisplayMemberPath);\n    var value = property.GetValue(item, null);\n    // Use the value here\n}	0
2555267	2555217	Recursively parse XmlDOcument	XDocument document = XDocument.Parse(xml); // xml string\nvar query = from file in document.Descendants("file")\n            select new\n                {\n                    Monitored = (int)file.Element("monitored"),\n                    Name = (string)file.Element("name"),\n                    Size = (int)file.Element("size")\n                };\n\nforeach (var file in query)\n{\n    Console.WriteLine("{0}\t{1}", file.Name, file.Size);\n}	0
15637239	15637112	How to release a lock on a JPG file	attachment.Dispose()	0
27719344	27719283	Excluding one item from list (by Index), and take all others	var result = numbers.Where((v, i) => i != MasterIndex).ToList();	0
18414247	18413865	nunit how to have a once off setup method (for all tests)	public class TestBase {\n     public TestBase() {\n       // Global setup\n     }\n}\n\npublic class MyTest : TestBase {\n     // Tests\n}	0
2553009	2552628	Using .net Datetime in sql query	Dim D = DateTime.Now.ToString(System.Globalization.CultureInfo.InvariantCulture)\n    '-or-\n    Dim D = DateTime.Now.ToString(New System.Globalization.CultureInfo("en-us"))	0
1051789	1049291	How to handle line breaks in data for importing with SQL Loader	SQL> CREATE TABLE EMP_50\n2 ORGANIZATION EXTERNAL\n3 ( TYPE oracle_datapump\n4 DEFAULT DIRECTORY dmp_dir\n5 LOCATION (???emp_50.dmp'))\n6 )\n7 AS SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 50\n8 ;	0
12688687	12563417	How to test connection to a data source in SSAS using C#	class ConnectivityTests\n{\n    // Variables\n    String serverName = "";\n    String databaseName = "";\n    String dataSourceName = "";\n\n    [Test]\n    public void TestDataSourceConnection()\n    {\n        try\n        {\n\n            // Creates an instance of the Server\n            Server server = new Server();\n            server.Connect(serverName);\n\n            // Gets the Database from the Server\n            Database database = server.Databases[databaseName];\n\n            // Get the DataSource from the Database\n            DataSource dataSource = database.DataSources.FindByName(dataSourceName);\n\n            // Attempt to open a connection to the dataSource.  Fail test if unsuccessful\n            OleDbConnection connection = new OleDbConnection(dataSource.ConnectionString);\n\n            connection.Open();\n        }\n        catch (Exception e)\n        {\n            Assert.Fail(e.ToString());\n        }\n        finally\n        {\n            connection.Close();\n        }\n\n     }\n}	0
7395748	7395436	strategies for error handling in a c# async lambda world?	asyncCall.Subscribe(result => DoSomething(result), ex => Oops(ex));	0
27436556	27436423	How can i disable a html control in the web-browser	webBrowser.Document.GetElementById("myCombo").Enabled = False '<--- for disable the control\n webBrowser.Document.GetElementById("myCombo").Enabled = True'<--- for enable the control	0
41175	41159	Fastest way to find common items across multiple lists in C#	var x = from list in optionLists\n        from option in list\n        where optionLists.All(l => l.Any(o => o.Value == option.Value))\n        orderby option.Value\n        select option;	0
26660419	26657780	Get user created date in sitecore	var users = Sitecore.Security.Accounts.UserManager.GetUsers();\n        foreach (Sitecore.Security.Accounts.User user in users)\n        {\n            var membershipUser = System.Web.Security.Membership.GetUser(user.Name, false);\n            if (membershipUser != null)\n            {\n                var date = membershipUser.CreationDate;\n            }\n        }	0
22523777	22523693	Is it possible to look at defined length in a string	string[] stringParts = columns[0].Split('-');\nint valueOfConcern = Convert.ToInt32(stringParts[1]);\nif (valueOfConcern >= 2999 && valueOfConcern <= 6000)\n{\n    //take your action\n}	0
19480886	19480849	Return multiple values from ArrayList C#	public List<string> vyhledavaniOS()\n{\n    List<string> listToReturn = new List<string>();\n\n    foreach (Vozidlo voz in nab?dka)\n    {\n        if (voz is Osobn?Vuz)\n            listToReturn.Add((voz.TypVozidla() + ": SPZ: " + voz.JakaSPZ + ", Znacka: " + voz.JakaZnacka + ", Barva: " + voz.JakaBarva));\n    }\n\n    return listToReturn;\n}	0
262743	262480	what's the quickest way to extract a 5 digit number from a string in c#	static string Search(string expression)\n{\n  int run = 0;\n  for (int i = 0; i < expression.Length; i++)\n  {\n    char c = expression[i];\n    if (Char.IsDigit(c))\n      run++;\n    else if (run == 5)\n      return expression.Substring(i - run, run);\n    else\n      run = 0;\n  }\n  return null;\n}\nconst string pattern = @"\d{5}";\nstatic string NotCached(string expression)\n{\n  return Regex.Match(expression, pattern, RegexOptions.Compiled).Value;\n}\n\nstatic Regex regex = new Regex(pattern, RegexOptions.Compiled);\nstatic string Cached(string expression)\n{\n  return regex.Match(expression).Value;\n}	0
18383423	18373308	Show context menu for some items in NSOutlineView	[Register("MySourceList")]\nprivate class MySourceList : NSOutlineView\n{\n    // Need this constructor for items created in .xib\n    public MySourceList(IntPtr handle) : base(handle)\n    { }	0
18555105	18555067	c# If else statement with case insensative	if(article.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0)\n{\n//   ....\n}\nelse\n{\n// .....\n}	0
30072521	30061118	performance monitor - getting current downloaded bytes	List<PerformanceCounter> instancesList = new List<PerformanceCounter>();\nprivate void InitializeCounter(string[] instances)\n{\n\n    foreach(string name in instances)\n    {\n        instancesList.Add(new PerformanceCounter("Network Interface", "Bytes Received/sec", name));\n    }\n\n}\nprivate void updateCounter()\n{\n    foreach(PerformanceCounter counter in instancesList)\n    {\n        bytes += Math.Round(counter.NextValue() / 1024, 2);\n        textBox1.Text = bytes.ToString();\n    }\n}	0
24315088	24213702	Embedding multiple files of different types into a single C# console application	string pathToSomeMsi = Path.GetTempFileName();\n\nusing (var resStream = Assembly.GetExecutingAssembly().GetManifestResourceStream("theMsi.msi"))\nusing (var fileStream = File.OpenWrite(pathToSomeMsi))\n{\n    resStream.CopyTo(fileStream);\n}\n\ninstallMsi(pathToSomeMsi);	0
4059050	4056469	Enumerate windows on taskbar in Windows XP without P/Invoke using C#	OnTopReplica/WindowSeekers/TaskWindowSeeker.cs	0
7568794	7568621	TextBox Column In DataGridView	private void Form1_Load(object sender, EventArgs e)\n{\n   DataTable dt = new DataTable();\n   dt.Columns.Add("c1", typeof(int));\n   dt.Columns.Add("c2");\n   for (int j = 0; j < 10; j++)\n   {\n      dt.Rows.Add(j, "aaa" + j.ToString());\n   }\n\n   this.dataGridView1.DataSource = dt;\n   this.dataGridView1.EditingControlShowing +=\n      new DataGridViewEditingControlShowingEventHandler(\n         dataGridView1_EditingControlShowing);\n}\n\nprivate bool IsHandleAdded;\n\nvoid dataGridView1_EditingControlShowing(object sender,\n    DataGridViewEditingControlShowingEventArgs e)\n{\n   if (!IsHandleAdded &&\n       this.dataGridView1.CurrentCell.ColumnIndex == 0)\n   {\n      TextBox tx = e.Control as TextBox;\n      if (tx != null)\n      {\n         tx.KeyPress += new KeyPressEventHandler(tx_KeyPress);\n         this.IsHandleAdded = true;\n      }\n   }\n}\n\nvoid tx_KeyPress(object sender, KeyPressEventArgs e)\n{\n   if (!(char.IsNumber(e.KeyChar) || e.KeyChar == '\b'))\n   {\n      e.Handled = true;\n   }\n}	0
18921159	18920971	ObservableCollection in Secondwindow	public class KeyListItem\n{ \n  public int Id { get; set; }\n  public string Name { get; set; }\n  public string Algorithm { get; set; }\n  public int Bits { get; set; }\n}	0
15157977	15157900	Getting one element from a strongly typed data set	if(bookCountDataTable.Rows.Count > 0)\n{\n     totalNumberOfBooks = Convert.ToInt32(bookCountDataTable.Rows[0]["TotalNumberOfBooks"]);\n}	0
20020346	20020311	How to wait for all the treads inside a loop to finish running	string[] rand_word = {apple, bannnana, cat, dog, eatttt}//5 words to check with the dictionary. Amount of words in here can vary later, that's why I am using a loop bellow\nstring likelihood = 0;\nList<Thread> threads = new List<Thread>();\nforeach (string line in rand_word)\n{        \n    Thread thread1 = new Thread(new ThreadStart(() => dictionary_match(line, ref likelihood)));\n    thread1.Start();\n    threads.Add(thread1);\n    Console.WriteLine("Value of likelihood Inside the Loop= " + likelihood); //Will show 0 since the dictionary_match function isn't finished running\n\n}\n\nConsole.WriteLine("Value of likelihood after the Loop= " + likelihood);//Will give 0 since the dictionary_match function isn't finished\n\nforeach (var thread in threads)\n{\n    thread.Join();\n}\n\nConsole.WriteLine("Final Value likelihood = " + likelihood); //After pausing for a while, dictionary_match function finished processing and gives an appropriate value for likelihood variable	0
15655626	15655204	"Sorting" a Tree Data Structure	insert_new( Node* node, value)\n    {\n\n    if(value > node->value)\n    {\n       if(node->right != null)\n       {\n         insert_new(node->right,value);\n       }\n       else\n       {\n         node->right = new Node(value);\n         return;\n       } \n   }\n   else\n   {\n      if(node->left != null)\n      {\n       insert_new(node->left,value)\n      }\n      else\n      {\n       node->left = new Node(value);\n       return;          \n      } \n   }\n}	0
19486327	19485909	add new row in gridview after binding C#, ASP.net	protected void Button1_Click(object sender, EventArgs e)\n   {\n       DataTable dt = new DataTable();\n       DataColumn dc = new DataColumn();\n\n       if (dt.Columns.Count == 0)\n       {\n           dt.Columns.Add("PayScale", typeof(string));\n           dt.Columns.Add("IncrementAmt", typeof(string));\n           dt.Columns.Add("Period", typeof(string));\n       }\n\n       DataRow NewRow = dt.NewRow();\n       NewRow[0] = TextBox1.Text;\n       NewRow[1] = TextBox2.Text;\n       dt.Rows.Add(NewRow); \n       GridView1.DataSource = dt;\n       GridViewl.DataBind();\n   }	0
23027777	23027762	Substring string URL with several delimiters	System.IO.Path.GetFileName("localhost/abcd/abcs/document.doc") //document.doc	0
7138606	7138565	passing a query string variable that is a keyword in c#	public ActionResult Index(string @event, string email, ...) {	0
929396	929349	Is there a way to build a new type during Runtime?	AssemblyBuilder assemblyBuilder = Thread.GetDomain().DefineDynamicAssembly(\n      assemblyName , AssemblyBuilderAccess.Run, assemblyAttributes);\nModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("ModuleName");\nTypeBuilder typeBuilder = moduleBuilder.DefineType(\n      "MyNamespace.TypeName" , TypeAttributes.Public);\n\ntypeBuilder.DefineDefaultConstructor(MethodAttributes.Public);\n\n// Add a method\nnewMethod = typeBuilder.DefineMethod("MethodName" , MethodAttributes.Public);\n\nILGenerator ilGen = newMethod.GetILGenerator();\n\n// Create IL code for the method\nilGen.Emit(...);\n\n// ...\n\n// Create the type itself\nType newType = typeBuilder.CreateType();	0
7796449	7795754	c# Remove rows from csv	string line;\n        StreamReader sr = new StreamReader(@"C:\Users\justin\Desktop\texts\First.txt");\n\n        StreamReader sr2 = new StreamReader(@"C:\Users\justin\Desktop\texts\Second.txt");\n\n        List<String> fileOne = new List<string>();\n        List<String> fileTwo = new List<string>();\n\n        while (sr.Peek() >= 0)\n        {\n            line = sr.ReadLine();\n            if(line != "")\n            {\n                fileOne.Add(line);\n            }\n        }\n        sr.Close();\n        while (sr2.Peek() >= 0)\n        {\n            line = sr2.ReadLine();\n            if (line != "")\n            {\n                fileTwo.Add(line);\n            }\n        }\n        sr2.Close();\n        var t = fileOne.Except(fileTwo);\n\n        StreamWriter sw = new StreamWriter(@"C:\Users\justin\Desktop\texts\First.txt");\n\n        foreach(var z in t)\n        {\n            sw.WriteLine(z);\n        }\n        sw.Flush();	0
1990417	1990395	In C#, what's the best way to spread a single-line string literal across multiple source lines?	string longString =\n    "Lorem ipsum dolor sit amet, consectetur adipisicing " + \n    "elit, sed do eiusmod tempor incididunt ut labore et dolore magna " + \n    "aliqua. Ut enim ad minim veniam.";	0
13881950	13880163	regex split with exceptions	public static string[] GetSplitStrings(string input)\n{\n    IList<string> splitStrings = new List<string>();\n    var counter = 0;\n\n    var sb = new StringBuilder();\n    var inLessGreater = false; // sometimes <> can contain "\n    foreach (var character in input)\n    {\n    if (character.Equals('<'))\n    {\n        inLessGreater = true;\n        counter++;\n    }\n\n    if (character.Equals('>'))\n    {\n        inLessGreater = false;\n        counter++;\n    }\n\n    if (character.Equals('"') && !inLessGreater)\n    {\n        counter++;\n    }\n\n    if ((character.Equals(' ') && counter == 0) || (counter == 2))\n    {\n        if (sb.ToString().Equals("") == false)\n        {\n        if (character.Equals('"') || character.Equals('>'))\n        {\n            sb.Append(character);\n        }\n        splitStrings.Add(sb.ToString());\n        }\n        sb.Clear();\n        counter = 0;\n    }\n    else\n    {\n        sb.Append(character);\n    }\n    }\n\n    return splitStrings.ToArray();\n}	0
8612140	8611760	How to make a property appear in the property grid for a control that i created?	using System.ComponentModel;\n\n[Category("Layout"), Description("Your Description Here"), DefaultValue(true)]\nbool  yourPropertyName\n{\n    .....\n}	0
888237	887924	How to expose functionality to PowerShell from within your application	protected override void ProcessRecord()\n{\n  // Get the current processes\n  Process[] processes = Process.GetProcesses();\n\n  // Write the processes to the pipeline making them available\n  // to the next cmdlet. The second parameter of this call tells \n  // PowerShell to enumerate the array, and send one process at a \n  // time to the pipeline.\n  WriteObject(processes, true);\n}	0
6859948	6859848	Creating and Consuming a C# Windows Service	protected override void OnCustomCommand(int command)	0
9439904	9439796	How to cast a Decimal to an int E6	GeoPoint point = new GeoPoint((int)(Latitude * 1E6), (int)(Longitude * 1E6));	0
3351360	3351345	How to delete files ,subdirectory entirely to specified path	Directory.Delete("the dir", true);	0
34156733	34155354	C# removing string before/after delimiter	using System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n    public static void Main()\n    {\n        Regex rgx = new Regex(@"?*\.*\(\w*\)\.*?*");\n        Console.WriteLine(rgx.Replace("(something)?keepThisOne", string.Empty));\n        Console.WriteLine(rgx.Replace("keepThisOne?(something)", string.Empty));\n        Console.WriteLine(rgx.Replace("(something)...keepThisOne?(somethingelse)", string.Empty));\n\n    }\n}	0
7740486	7740181	How to call a method with arguments of different types using reflection in C#	wsType.GetMethod(function, BindingFlags.Static | BindingFlags.Public | BindingFlags.Instance);	0
3913239	3913206	comparing two objects by two properties	public int Compare(Person p1, Person p2)\n{\n    int primary = p1.Name.CompareTo(p2.Name);\n    if (primary != 0)\n    {\n        return primary;\n    }\n    // Note reverse order of comparison to get descending\n    return p2.Age.CompareTo(p1.Age);\n}	0
13414676	13414277	SQLDataReader doesnt show first element, but accesses it?	string x = string.Empty;\nint index = sdr.GetOrdinal("x");\nif (!sdr.IsDBNull(index))\n     x = sdr.GetString(index);\n\nlong? y;\nindex = sdr.GetOrdinal("y");\nif (!sdr.IsDBNull(index))\n    y = sdr.GetInt64(index);	0
5993929	5993889	Dynamically select and update a column value in LINQ resultset	foreach (BloodBank b in stockDetails)\n{\n    FieldInfo f = typeof(BloodBank).GetField("fieldName");\n    if (f != null)\n    {\n       f.SetValue(b, TextBox1.Text);\n    }\n}	0
15478179	15478006	Simple User configurable settings file	[Serializable]\npublic class SettingItem\n{\n    public string Name { get; set; }\n    public string Value { get; set; }\n}\n\nprivate List<SettingItem> ProjSettings = new List<SettingItem>();\nProjSettings.Add(new SettingItem {Name = "SomeKey", "SomeValue"});	0
6962314	6961929	Load Project Settings from .NET Assembly	foreach ( AssemblyName assemName in assemComponents )\n{\n    foreach ( var type in Assembly.Load( assem ).GetTypes() )\n    {\n        // look for classes that derive from SettingsBase named "Settings"\n        if ( type.Name == "Settings" && typeof( SettingsBase ).IsAssignableFrom( type ) )\n        {\n            // get the value of the static Default property\n            var defaults = (SettingsBase)type.GetProperty( "Default" ).GetValue( null, null );\n\n            // walk the property list and get the value from the Default instance\n            foreach ( SettingsProperty prop in defaults.Properties )\n            {\n                Debug.WriteLine( string.Format( "{0}: {1}", prop.Name, defaults[ prop.Name ] ) );\n            }\n        }\n    }\n}	0
33045880	33045157	C# RegEx remove everyting before syncML xml payload of a line	string s = line.Substring(line.IndexOf("<?xml "));	0
5472423	5472172	How do you disable an item in listview control in .net 3.5	private void listView1_ItemCheck(object sender, ItemCheckEventArgs e) {\n        // Disable checking odd-numbered items\n        if (e.Index % 2 == 1) e.NewValue = e.CurrentValue;\n    }	0
26436336	26436298	WPF how to easily chain animations in code behind?	private void button_Click(object sender, RoutedEventArgs e)\n    {\n        ThicknessAnimation animate = new ThicknessAnimation(new Thickness(0, -40, 0, 0), TimeSpan.FromSeconds(1));\n        animate.Completed += new EventHandler(animate_Completed);\n\n        testCanvas.BeginAnimation(Canvas.MarginProperty, animate);\n    }\n\n    private void animate_Completed(object sender, EventArgs e)\n    {\n        testLabel.Content = "ANIMATION TEST";\n\n        testCanvas.BeginAnimation(Canvas.MarginProperty,\n            new ThicknessAnimation(new Thickness(0, 0, 0, 0), TimeSpan.FromSeconds(1))\n        );\n    }	0
9019778	9019638	Using linq to query a nullable field	Dictionary<int, QualificationLevel> unitsWithLevels = \nfilteredCollection\n.Where(x => x.QualificationLevel != null \n&& SearchCriterionQualificationUnitLevels.Any(unitLevel => unitLevel.Equals(x.QualificationLevel.Value)));	0
21703603	21703008	Force CCNet project build from C# application or command line	CruiseControl.Net Command-Line Utility\nProvides command-line access to a CruiseControl.Net server\n\nCCCmd <command> [options]\n\ncommand: one of the following actions\n  help:         display this help screen\n  retrieve:     retrieve details on a project or server\n  forcebuild:   forces a build on a project\n  abortbuild:   aborts a build on a project\n  startproject: starts a project integrator\n  stopproject:  stops a project integrator	0
3872167	3871973	insert XmlDocument into a XmlDocument node	XmlNode requestNode =  bigDoc.FirstChild;\nrequestNode.AppendChild(\n    requestNode.OwnerDocument.ImportNode(\n        anotherXMLDocument.DocumentElement, true));	0
34280675	34279769	How to optimize LINQ-2-SQL expression?	var merged = this.DB.Links\n        .Where(l=>l.INSTANCE_ID==123456 && l.CONTACT_ID.HasValue && l.ORGANISATION_ID.HasValue)\n        .GroupBy(l => l.CONTACT_ID)\n        .SelectMany(s => s.Where(x => s.Count() == 1 || x.DEFAULT_LINKED_ORGANISATION)\n                          .Select(link => link.LINK_ID));	0
29863218	29862892	Shooting to the center of the screen	float x = Screen.width / 2f;\nfloat y = Screen.height / 2f;\n\nvar ray = Camera.main.ScreenPointToRay(new Vector3(x, y, 0));\nclone.velocity = ray.direction * laserSpeed;	0
16416562	16416467	Having sql connection open for a long time	using(SqlConnection con = new SqlConnection(.....))\n{\n   ... do your work with the database here ....\n}	0
19637028	19630085	How do I open XML from link in razor?	var xml = XDoxument.Load("https://ws1.webservices.nl/rpc/get-simplexml/blah/blah");	0
6618903	6618847	LINQ - GroupBy a key and then put each grouped item into separate 'buckets'	var groups = items.GroupBy(item => item.ListId);\n\nforeach(var group in groups)\n{\n     Console.WriteLine("List with ID == {0}", group.Key);\n     foreach(var item in group)\n        Console.WriteLine("    Item: {0}", item.ItemName);\n}	0
12184184	12184142	Group two columns into one and return	...\ngroup s by new {s.StudentID, s.StudentName} into g\n...	0
5961186	5961158	i have a problem with dropdownLists	// add this line - it's different from ClearSelection()\nSubTopicDropDownList.Items.Clear();\n\nforeach (string item in chosenItem)\n{\n    SubTopicDropDownList.Items.Add(item);\n}	0
22010891	22010754	Why use member variables in a class	private string _name;\npublic string Name\n{\n   get{ return _name; }\n   set\n   {\n      SomeHandler("Name", value);\n      _name = value;\n   }\n}	0
13998170	13998040	Convert Join and Group By from SQL to LINQ	var userDetail =\n    context.Orders\n        .GroupBy(i => i.UserId_Fk)\n        .Select(i => new {\n                         UserId_Fk = i.Key,\n                         OrderCount = i.Count(),\n                         ProductQuantity = i.Sum(j => context.OrderDetails.Where(k=> k.OrderId_Fk == j.OrderId).Sum(k=> k.Quantity))\n                      });	0
11490003	11474320	Install to same path when upgrading application	[TARGETDIR]	0
23521947	23521595	Bulk inserting to MongoDB on Replicaset	IEnumerable<WriteConcernResult> results = collection.InsertBatch(records)	0
18877968	18833153	EF Code First Model definition for one to one mapping with cascade delete	public class Member\n{\n    [Key]\n    public int Id { get; set; }\n\n    public virtual Address Address { get; set; }\n}\n\npublic class Address\n{\n    [Key]\n    public int MemberId {get;set;}\n}\n\nprotected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder\n        .Entity<Address>()\n        .HasKey(t => t.MemberID);\n\n    modelBuilder\n        .Entity<Member>()\n        .HasRequired(t => t.Address)\n        .WithRequiredPrincipal();\n}	0
4639615	4639593	Is it possible to make alias for a variable in C#?	Func<SomeClass> c1 = () => Program.someClass;	0
21686891	21686766	populate dropdownlist with all numbers in between 2 numbers	private IEnumerable<int> GetAgesBetween(string agesText) {\n    var parts = agesText.Split('-');\n    var start = int.Parse(parts[0].Trim());\n    var end = int.Parse(parts[1].Trim());\n    return Enumerable.Range(start, 1 + end-start);\n}	0
4614019	4613933	Would like to Show the form N number of times when user enter a Number in a text box	//on main form:\nint i = 0; \n//parse the textbox1.text to int and check the result:\nif(!int.TryParse(textbox1.Text,out i)||i<0||i>9999)\n{\n  //incorrect int value \n  MessageBox.Show("Please enter a valid value");\n}\nelse //correct int value\n{\n  subform mysub=new subform(i);\n  subform.ShowDialog();\n}\n//on your subform:\nint timebeforeclose=0;\npublic subform(int count)\n{\n  timebeforeclose=count;\n}\n\nprivate void btnSave_Click(object sender, EventArgs e)\n{\n  //1.save your data or whatever...\n  //2.empty any fields you want..\n  //update timebeforeclose:\n  timebeforeclose--;\n  //check the timebeforeclose:\n\n  if(timebeforeclose==0)\n  {\n    this.Close(); //close this form when reaches the specified number.\n  }      \n}	0
15379130	15379086	Finding server(s) capacity	distributed mode	0
2945289	641401	Disable antialiasing for a specific GDI device context	ImportAddressTable.cs	0
17890284	17881725	Control That Can OverLeap WebBrowser Control	Hosting a Windows Forms Control in WPF	0
3255220	3252241	Using generic arguments on WPF Window defined in XAML	x:TypeArguments	0
11325918	11325864	LINQ to XML returns no result	XNamespace xn = "http://webService";\ndoc.Descendants(xn + "downloadInfoReturn")	0
15859371	15859109	.Net Regex Replace - Multiline while searching for filepaths	string pathToRemove = @"c:\\outputpath\\";\nRegex sourceRegex = new Regex(pathToRemove, RegexOptions.IgnoreCase);\nstring sanity = sourceRegex.Replace(input, string.Empty);	0
7146723	7146690	Add Properties to a base class so they show on Visual Studio's Properties window?	public class CameraWindow : PictureBox\n{\n    [Browsable(true)]\n    public int MyProperty{get;set;}\n}	0
7056367	7056351	How can I calculate the sum. of the values in a dataGridView column?	int sum = 0;\n\nforeach (DataGridViewRow row in dataGridView.Rows)\n{\n    //here 0 is the index of columns you want to get values from \n    // you can also use column name instead of index\n    sum += (int) row.Cells[0].Value;\n}\n\n//for showing the user message box\nMessageBox.Show("Sum of all the values is {0}", sum.ToString());	0
10300644	10300551	Simple application to populate an asp.net Gridview	gvProjectList.DataBind();	0
13893707	13893675	EF inserting object to DB getting validation error	public class User\n{\n    public int Id { get; set; }\n    public string Name { get; set; }\n    public string Surname { get; set; }     \n    public int CountryId { get; set; }\n\n    [ForeignKey("CountryId")]\n    public virtual Country Country { get; set; }\n}\n\npublic class Country\n{\n    public int Id { get; set; }\n    public string CountryName { get; set; }\n\n    public virtual ICollection<User> Users { get; set; }\n}\n\nUser user = new User()\n{\n     Name = model.Name,\n     Surname = model.Surname,  \n     CountryId = 1;\n};	0
31863759	31863551	Truncating a version number C#	String version = "1.0.420.50.0";\nString [] versionArray = version.Split(".");\nvar newVersion = string.Join(".", versionArray.Take(4));	0
3761591	3761564	C# console app - explicit termination (not Env..Exit)	class Program\n{\n    static void Main()\n    {\n        ConsoleKeyInfo cki;\n\n        do\n        {\n            Console.Write("Press a key: ");\n            cki = Console.ReadKey(true);\n            Console.WriteLine();\n\n            if (cki.Key == ConsoleKey.D1)\n            {\n                Console.Write("You pressed: 1");\n            }\n        }\n        while (cki.Key != ConsoleKey.D2);\n\n    } // <-- application terminates here\n}	0
3537661	3537657	c# - how to create an array from an enumerator	IEnumerable<byte> udpDnsPacket = /*...*/;\n\nbyte[] result = udpDnsPacket.ToArray();	0
634145	634142	How to get a path to the desktop for current user in C#?	string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);	0
21611462	21611352	how can I determine memory usage of a giant c# data set	System.Diagnostics.PerformanceCounter	0
12276593	12276533	Check if an element exists in XML	if(configuration.Elements("...").Any()){...}	0
3311617	3265212	How to send an XDocument via MSMQ (using WCF)?	messageQueue.Formatter = new System.Messaging.XmlMessageFormatter(new Type[] { typeof(System.String) });	0
12521559	12521501	How do you re-try a try after you've handled an exception?	bool ok = false; \n\nwhile(!ok)\n{    \n    try\n    {\n        TryWritingToFile();          \n        ok = true; \n    }\n    catch (Exception)\n    {\n        CreateFile();\n        //now I want to go back and try to write to the file again. \n    }\n}	0
7737188	7736831	Group by in DataTable Column sum	Dictionary<string, int> dicSum = new Dictionary<string, int>();\n    foreach (DataRow row in dt.Rows)\n    {\n        string group=row["Group"].ToString();\n        int rate=Convert.ToInt32(row["Rate"]);\n        if (dicSum.ContainsKey(group))\n            dicSum[group] += rate;\n        else\n            dicSum.Add(group, rate);\n    }\n    foreach (string g in dicSum.Keys)\n        Console.WriteLine("SUM({0})={1}", g, dicSum[g]);	0
19206304	19201563	Creating a Thumbnail through AudioVideoCaptureDevice	private void SaveThumbnail()\n        {\n            Deployment.Current.Dispatcher.BeginInvoke(() =>\n            {\n                var w = (int)_videoCaptureDevice.PreviewResolution.Width;\n                var h = (int)_videoCaptureDevice.PreviewResolution.Height;\n\n                var argbPx = new Int32[w * h];\n\n                _videoCaptureDevice.GetPreviewBufferArgb(argbPx);\n                var wb = new WriteableBitmap(w, h);\n                argbPx.CopyTo(wb.Pixels, 0);\n                wb.Invalidate();\n\n                using (var isoStore = IsolatedStorageFile.GetUserStoreForApplication())\n                {\n                    var fileName = _isoVideoFileName + ".jpg";\n\n                    if (isoStore.FileExists(fileName))\n                        isoStore.DeleteFile(fileName);\n\n                    var file = isoStore.CreateFile(fileName);\n                    wb.SaveJpeg(file, w, h, 0, 20);\n                    file.Close();\n                }\n            });\n        }	0
24668454	24668299	C# Updating label with image	label1.AutoSize = false	0
14943273	14942105	DataTable as DataGrid.ItemsSource	DGrid.ItemsSource = dt.AsDataView();	0
18389752	18389730	Getting a list of strings via LINQ	List<List<string>> rows = (from myRow in data.AsEnumerable()\n                            select new List<string> {myRow["FirstName"].ToString(),\n                                myRow["LastName"].ToString(),\n                                myRow["Department"].ToString(),\n                                myRow["Birthdate"].ToString(),\n                                myRow["Description"].ToString()\n                            }).ToList();	0
11267404	11207932	RavenDB search for each of multiple terms using StartsWith	var searchTerms = "John Doe".Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n\nvar query = session.Advanced.LuceneQuery<Person, PersonIndex>();\nquery = query.OpenSubclause(); // optional\n\nforeach (var term in terms)\n{\n    query = query.WhereStartsWith("FirstName"), term).OrElse();\n    query = query.WhereStartsWith("LastName"), term).OrElse();\n}\n\nquery = query.WhereEquals("Id", null);\nquery = query.CloseSubclause(); // if OpenSubclause() was used	0
21192496	21191765	Using an IP address for a WCF Service	MyClient client = new MyService.MyClient();\nclient.Endpoint.Address = new EndpointAddress(new Uri("target URL"));\nclient.Open();	0
12576289	12576252	Convert JavaScript RegEx to C# RegEx for email validation	public bool IsValidEmailAddress(string emailAddress)\n{\n    try\n    {\n        MailAddress m = new MailAddress(emailAddress);\n        return true;\n    }\n    catch (FormatException)\n    {\n        return false;\n    }\n}	0
4250515	4248236	Drawing a path between two points	Vector2 IntermediatePoint(Vector2 p0, Vector2 p1, float t)\n{\n    Vector2 delta = p1 - p0;\n\n    float distance = delta.Length();\n\n    if (distance == 0.0f)\n    {\n        return p0;\n    }\n    else\n    {\n        Vector2 direction = delta / distance;\n\n        return p0 + direction * (distance * t);\n    }\n}	0
11133145	11133047	Linq query to select top 20 items of a list with a length restriction on its property	context.tagService.GetTagList().Where(x => x.tag.name.Length < 20 \n                                   && x.tag.name.Length>4)\n                               .Take(20).ToList();	0
30510403	30510049	How to dispose a System.Diagnostics.Process object without killing process?	class Program\n{\n    static void Main(string[] args)\n    {\n        Process p = new Process\n        {\n            StartInfo = {FileName = "notepad.exe"}\n        };\n        p.Start();\n\n        p.Dispose();\n        // Notepad still runs...\n        GC.Collect(); // Just for the diagnostics....\n        // Notepad still runs...\n        Console.ReadKey();\n    }\n}	0
24989409	24947598	Set row color of Telerik RadGrid	using System.Drawing;\n\nprotected void RadGrid1_ItemDataBound(object sender, Telerik.Web.UI.GridItemEventArgs e)\n {\n  if (e.Item is GridDataItem)\n    {\n     TableCell celltoVerify1 = dataBoundItem["status"];\n       if (celltoVerify1.Text== "REJECTED")\n        {\n            celltoVerify1.ForeColor =  Color.Red;\n            //celltoVerify1.Font.Bold = true;\n            //celltoVerify1.BackColor = Color.Yellow;\n        }\n    }\n }	0
13012609	13012548	Does C# generate concrete implementation for unused template parameters?	protected static List<TSub> MyStaticList = BaseUtil.MyStaticList	0
19318658	19266948	c# SAP NetWeaver Connection via OData	string uri = "http://services.odata.org/OData/OData.svc/Products" \nstring odataQuery = "?$format=json"\nvar request = WebRequest.Create(uri+"/"+odataQuery);\nrequest.Method = "GET";\nvar reader = new StreamReader(stream: request.GetResponse().GetResponseStream());\nstring neededData = reader.ReadToEnd(); //json format	0
8287614	8287569	Integer to byte with given number of bits set	int n = 3; // 0..8 \nint mask = 0xFF00;\nbyte result  = (byte) (mask >> n);	0
26421114	26420819	Hot to display binary image from db to image box.?8	Image1.ImageUrl = "data:image/jpeg;base64," + base6;	0
14560777	14560674	Forward current page HTML back to server	document.getElementById('<%= hidHTML.ClientID %>').value = encodeURI(document.body.innerHTML);	0
25111416	25111258	Post JSON to mvc Controller sending null/default value not value I passed in	public class GameResultModel\n{\n    public int WinnerUserId { get; set; }\n    public int LoserUserId { get; set; }\n}	0
12585917	12572331	Convert CSS Selector to XPATH	String css = "div#test .note span:first-child";\nString xpath = css2xpath.Transform(css);	0
10988396	10987594	Winforms Which Design Pattern / Agile Methodology to choose	you need to have solid Unit Tests	0
18665150	18665081	Change color of an asp.net button on mouse hover using css	.HeaderBarThreshold:hover a\n{\n     color: Red !important; // !important may not be necessary \n}	0
9864397	9864363	How to programmatically compile a c code from a c# code using mingw32-gcc compiler	string szMgwGCCPath = "C:\\mingw32\\bin\\mingw32-gcc.exe"; // Example of location\nstring szArguments = " -c main.c -o main.exe"; // Example of arguments\nProcessStartInfo gccStartInfo = new ProcessStartInfo(szMgwGCCPath , szArguments );\ngccStartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nProcess.Start(gccStartInfo );	0
13939591	13939411	how to insert values in sql server through radio button	cmd.Parameters.AddWithValue("@gender", genderCombo.SelectedValue);	0
11359394	11356294	Find the file name of zip file in the given url path	string urlpath = "http://www.example.com/folder/"\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(urlpath);\n    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n    {\n       using (StreamReader reader = new StreamReader(response.GetResponseStream()))\n       {\n           string html = reader.ReadToEnd();\n           Regex regEx = new Regex(@".*/(?<filename>.*?)\.zip");\n           MatchCollection matches = regEx.Matches(html);\n           if (matches.Count > 0)\n           {\n                foreach (Match match in matches)\n                {\n                  if (match.Success)\n                  {\n\n                    Console.WriteLine(match.Groups["filename"].Value);\n                  }\n            }\n       }\n\n   }	0
2377613	2377557	How to obtain the path of the application in smart device application?	string path;\n path = System.IO.Path.GetDirectoryName( \n System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase );	0
21890430	21890330	Nodes selection inside HtmlNodeCollection with HTML Agility Pack	var nodes = doc.DocumentNode.SelectNodes("//div[@class='class1']");\n\nvar nodes2 = nodes.Select(c1 => c1.SelectNodes("div[@class='class2']"));	0
30194344	30194195	Array of async tasks. Can I attach metadata to each task?	var tasks = users.Select(async user =>\n{\n    var products = await this.repository.GetProducts(user.UserName);\n    return new { user, products };\n});\nvar results = await Task.WhenAll(tasks);\nvar resultsAsDictionary = results(x => x.user, x => x.products);	0
27712985	27712902	Sort a list of navigation links alphabetically	foreach (Item MarketItem in MarketSet.OrderBy(x => x.Fields["Menu Title"].Value))\n  MarketLinks.Text += string.Format("<a href=\"{0}\">{1}</a>", ScHelper.GetRegionPath(MarketItem), MarketItem.Fields["Menu Title"].Value);	0
758191	758066	How to mock Controller.User using moq	[TestMethod]\n    public void HomeControllerReturnsIndexViewWhenUserIsAdmin() {\n        var homeController = new HomeController();\n\n        var userMock = new Mock<IPrincipal>();\n        userMock.Expect(p => p.IsInRole("admin")).Returns(true);\n\n        var contextMock = new Mock<HttpContextBase>();\n        contextMock.ExpectGet(ctx => ctx.User)\n                   .Returns(userMock.Object);\n\n        var controllerContextMock = new Mock<ControllerContext>();\n        controllerContextMock.ExpectGet(con => con.HttpContext)\n                             .Returns(contextMock.Object);\n\n        homeController.ControllerContext = controllerContextMock.Object;\n        var result = homeController.Index();\n        userMock.Verify(p => p.IsInRole("admin"));\n        Assert.AreEqual(((ViewResult)result).ViewName, "Index");\n    }	0
12794254	12657006	How to check whether it is password-protected excel file using EPPlus?	Workbook book = ****xyz****;\nif (book.HasPassword)\n{\n    book.Password = Properties.Settings.Default.ExcelFilePW;\n    MessageBox.Show("Excel file is encrpyted");\n}	0
13662583	13662281	Change an int value at runtime	private void button2_Click(object sender, EventArgs e)\n    {\n        if (iCount == 0)\n        {\n            iTemp = 20;\n            iCount++;\n        }\n        iTemp = iTemp - 1;\n        MessageBox.Show(iTemp.ToString());\n    }\n}	0
20844279	20774750	how to detect two hot key in win form app like CTRL +C , CTRL+ W	private bool _isFirstKeyPressedW = false;\n\nprivate void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n    if (e.Control & e.KeyCode == Keys.W) \n    {\n        _isFirstKeyPressedW = true;\n    }\n    if (_isFirstKeyPressedW) \n    {\n        if (e.Control & e.KeyCode == Keys.S) \n        {\n            //write your code \n        } \n        else \n        {\n            _isFirstKeyPressedW = e.KeyCode == Keys.W;\n        }\n    }\n}	0
27488579	27488313	opening a text file with excel opentext file using C#	_wbs.OpenText(Path:=pathTemp,Datatype:=xlDelimited,Other:=True,Otherchar:="*");	0
11644228	11644145	How to remove spaces in path?	Process regeditProcess = Process.Start("regedit.exe", "/s \"C:\\Program Files\\Test Folder\\sample.reg\"");	0
24379918	24379694	How can I return a value inside Select() Lambda Expression	Call service first then assign result.\n\nvar benefits = customerBenefits\n                        .Select(n => {\n                            var user = serService.GetByUserID(n.AddedByUserID.Value);\n\n                            return new CustomerBenefit(\n                                n.BenefitID,                   \n                                n.AddedByUserID.HasValue ? (user== null ? String.Empty : ).DisplayName) : n.AddedByAgentID,\n                                n.Reason} );	0
32404521	32403542	Using TempData with returnview()	int id = (int)(TempData["ID"]);	0
19916910	19916800	No overload for method 'setAttribute' takes '2' arguments	Element.setAttribute("width", Element.offsetWidth, 0);\nElement.setAttribute("height", Element.offsetHeight, 0);\nElement.setAttribute("src", "images/newimage.png", 0);	0
10715738	6119505	How to overcome PathTooLongException?	.NET Base Class Libraries : Long Path	0
6935416	6935264	group by with multiple columns using lambda	var query = source.GroupBy(x => new { x.Column1, x.Column2 });	0
17638185	17637950	convert string of hex to string of little endian in c#	static string LittleEndian(string num)\n{\n    int number = Convert.ToInt32(num, 16);\n    byte[] bytes = BitConverter.GetBytes(number);\n    string retval = "";\n    foreach (byte b in bytes)\n        retval += b.ToString("X2");\n    return retval;\n}	0
8053810	8053688	Generic Extensions	public static AceDataObjectCollection<T> ToAceDataObjectCollection<T>(this IEnumerable<T> col) where T : IAceDataObject \n{    \n   AceDataObjectCollection<T> objects = new AceDataObjectCollection<T>();\n\n   foreach (T item in col)\n      objects.Add(item);\n\n   return objects; \n}	0
18926951	17343101	How to provide description of update with ClickOnce?	using System.Deployment.Application;\n...\n\nprivate void DisplayChangeLog()\n{\n    if (!ApplicationDeployment.IsNetworkDeployed)\n        return;\n\n    if (!ApplicationDeployment.CurrentDeployment.IsFirstRun)\n        return;\n\n    ThreadPool.QueueUserWorkItem(state =>\n        Execute.OnUIThread(() => <Pop up window with latest changes> ));\n}	0
18014853	18014785	Sort a list of DataRow	private static int MyComp(DataRow left, DataRow right)\n{\n    if (left["ID"] == right["ID"])\n    {\n       return 0;\n    } \n    else\n    {\n       return 1;\n    }\n}\n\nlst.Sort(MyComp)	0
29397177	29396658	Programatically enable RichTextBox and show caret	Dispatcher.BeginInvoke(\n    new Action(delegate()\n    {\n        contentBox.Focus();         // Set Logical Focus\n        System.Windows.Input.Keyboard.Focus(contentBox); // Set Keyboard Focus\n    })\n);	0
24883755	24869237	ASP Repeater control with multiple templates	public override void DataBind()\n    {\n        foreach (var item in (IEnumerable<LifestreamItem>)this.DataSource)\n        {\n            if (item is LifestreamTwitterItem)\n            {\n                TwitterTemplate.InstantiateIn(item); // instantiate inside the item which is also a control.\n            }\n            else\n            {\n                ItemTemplate.InstantiateIn(item);\n            }\n            item.DataBind(); // bind the item\n            Controls.Add(item); // add the item to the repeater\n        }\n    }	0
26695583	26695565	Finding average in an array without using array class	int sum = 0;\nforeach (int scores in bowlerScores)\n{\n    sum += scores;\n}\ndouble average = (double)sum / (double)SCORE_COUNT;	0
712210	712198	find non intersecting data set with linq	var nonIntersecting = a.Union(b).Except(a.Intersect(b));	0
22798251	22798227	How to convert binary text to a string?	string s = Encoding.UTF8.GetString(fileBytes);	0
3929521	3929153	Prevent row selection in datagrid when clicking on a checkbox cell	void dataGridView_CellMouseClick(object sender, DataGridViewCellMouseEventArgs e)\n    {\n        // Make sure it is a left click\n        if(e.Button == MouseButtons.Left)\n        {\n            // Make sure it is on a cell\n            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)\n            {\n                // Only allow certain columns to trigger selection changes (1 & 2)\n                if (e.ColumnIndex == 1 || e.ColumnIndex == 2)\n                {\n                    // Set my own private selected row index\n                    setSelectedRow(e.RowIndex);\n                }\n                else\n                {\n                    // Actions for other columns...\n                }\n            }\n        }\n    }	0
5104372	5104327	Download a File From a External sever through Asp.net & C#	WebClient webClient = new WebClient();\nwebClient.DownloadFile(remoteFileUrl, localFileName);	0
4346440	4346431	LINQ How to select more than 1 property in a lambda expression?	MyList.Select(x => new { x.Id, x.Name }).ToList();	0
31696862	31696725	convert SqlByte datatype to byte in c#	SqlByte x = 2;\nint y;\ny = (int) x;	0
7575202	7573596	Add an excel column header to single header using c sharp	// Type _ = Type.Missing;\nwkSheet.Range["A1", _].Value2 = "Heading 1";\nwkSheet.Range["B1", _].Value2 = "Heading 2";\nwkSheet.Range["C1", _].Value2 = "Heading 3";	0
1331830	1331819	How can I display a symbol in a string with c#?	string oneWay = "5 ? 7";\nstring anotherWay = "5 \u00F7 7";	0
13056265	13056230	Copy bits from ulong to long in C#	ulong value1 = 0xFEDCBA9876543210UL;  // 18364758544493064720\nlong value2 = (long)value1;           // -81985529216486896\nulong value3 = (ulong)value2;         // 18364758544493064720	0
14643599	14461262	Word Interop Copy Formated Text of Table Cell	var copyFrom = agendaTable.Rows[i].Cells[1].Range;\nvar copyTo = otherTablesRow.Cells[1].Range;\n\ncopyFrom.MoveEnd(WdUnits.wdCharacter, -1);\ncopyTo.FormattedText = copyFrom.FormattedText;	0
30916494	30914915	Is this a bug in resharper?	List<string> duplicateLabelsList = allResourcesLookup.SelectMany(x => x).Select(x => x.LoaderOptions.Label).Duplicates<string, string>().ToList(); ; \nif (duplicateLabelsList.Any()) \nthrow new DuplicateResourceLoaderLabelsException(duplicateLabelsList);	0
13160723	13160549	Gridview update button	foreach (GridViewRow row in gvUsers.Rows)\n    {\n        TextBox txtFirstName = row.FindControl("txtFirstName") as TextBox;\n        TextBox txtLastName = row.FindControl("txtLastName") as TextBox;\n\n        if (txtFirstName.Text!="" && txtLastName.Text!="")\n        {\n           // do what you need with values\n        }\n\n    }	0
12843742	12843676	Rename a column using a lambda expression	var persons = person.Select(c=> new {\n               name = c.firstname\n               //other attributes here \n                });	0
27628621	27628516	How can i parse specific char/letter from string and add it to a List<string>?	List<string> test1 = txtDir.Text.Split('/').ToList();	0
7851126	7851089	How to set DataGridViewCell.Value with Option Strict On	If DataGridViewCell.Value.ToString() = "some value" Then	0
5743287	5743243	Convert DateTime with TypeDescriptor.GetConverter.ConvertFromString (using custom format)	public class CustomDateTimeTypeConverter : TypeConverter\n{\n    public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)\n    {\n        return DateTime.ParseExact(value.ToString(), "yyyy-MM-dd HH-mm-ss", culture);\n    }\n}\n\n[TypeConverter(typeof(CustomDateTimeTypeConverter))]\nstruct AdvancedDateTime\n{\n}\n\n[TestFixture]\npublic class DateTime\n{\n    [Test]\n    public void TypeConvert_StrangeFormat_ConvertsWithoutProblem()\n    {\n        string datetime = "2011-04-21 23-12-13";\n        TypeConverter converter = TypeDescriptor.GetConverter( typeof (AdvancedDateTime) );\n        var convertedFromString = converter.ConvertFromString(datetime);\n        Assert.AreEqual(new DateTime(2011,4,21, 23,12,13), convertedFromString);\n    }\n}	0
11863564	11863382	Scraping from middle of string with regex	var str = "name(name, content(content, content, content), number)";\nConsole.WriteLine(str.Substring(0, str.IndexOf(',')) + str.Substring(str.LastIndexOf(',')) );	0
10773905	10773655	How to fill color in a shape drawn by pen	using System.Drawing.Drawing2D;\n...\n    public partial class Form1 : Form {\n        public Form1() {\n            InitializeComponent();\n            panelPath = new GraphicsPath();\n            panelPath.AddCurve(new Point[] { new Point(470, 470), new Point(430, 440), new Point(400, 480), new Point(470, 560), });\n            panelPath.AddCurve(new Point[] { new Point(470, 470), new Point(510, 440), new Point(540, 480), new Point(470, 560), });\n            panel1.Paint += new PaintEventHandler(panel1_Paint);\n        }\n\n        void panel1_Paint(object sender, PaintEventArgs e) {\n            e.Graphics.TranslateTransform(-360, -400);\n            e.Graphics.FillPath(Brushes.Green, panelPath);\n            e.Graphics.DrawPath(Pens.Red, panelPath);\n        }\n        GraphicsPath panelPath;\n    }	0
11823004	11822653	equivalent PHP sha1 in C#, with raw binary format and a length of 20	string sampletext = "text";\nSystem.Security.Cryptography.SHA1 hash = System.Security.Cryptography.SHA1CryptoServiceProvider.Create();\nbyte[] plainTextBytes = Encoding.UTF8.GetBytes(sampletext);\nbyte[] hashBytes = hash.ComputeHash(plainTextBytes);\n\nforeach (byte b in hashBytes) {\n    Console.Write(string.Format("{0:x2}", b));\n}	0
538714	538695	How to get the same time and Day next month using DateTime in c#	using System;\nusing System.Net;\n\npublic class Test\n{\n    static void Main(string[] args)\n    {\n        Check(new DateTime(2005, 1, 12));\n        Check(new DateTime(2009, 2, 28));\n        Check(new DateTime(2009, 12, 31));\n        Check(new DateTime(2000, 1, 29));\n        Check(new DateTime(2100, 1, 29));\n    }\n\n    static void Check(DateTime date)\n    {\n        DateTime? next = OneMonthAfter(date);\n        Console.WriteLine("{0} {1}", date,\n                          next == null ? (object) "Error" : next);\n    }\n\n    static DateTime? OneMonthAfter(DateTime date)\n    {\n        DateTime ret = date.AddMonths(1);\n        if (ret.Day != date.Day)\n        {\n            // Or throw an exception\n            return null;\n        }\n        return ret;\n    }\n}	0
9975911	9975445	ExtJS cannot decode JSON message	{\n    "success": true,\n    "message": "test"\n}	0
15297739	15297187	Unity: How to inject a singleton with two interfaces, where one type mapping needs to be named?	var container = new UnityContainer();\n\n        var manager = container.Resolve<EventManager>();\n        container.RegisterInstance<IEventManager>(manager, new ContainerControlledLifetimeManager());\n        container.RegisterInstance<IEventSource>("EventManager", manager, new ContainerControlledLifetimeManager());\n\n        container.RegisterType<IEventSource, EventSourceA>("EventSourceA");\n        container.RegisterType<IEventSource, EventSourceB>("EventSourceB");\n        container.RegisterType(typeof(Component));\n\n        container.Resolve<Component>();	0
16534202	16534153	Change Background image every visit	public getBackground (HttpSessionState session) {\n    String bg = (string) session["session.randomBG"];\n    if (bg == null) {\n        // pick a random BG & store  it.\n        bg = "pick one";\n        session["session.randomBG"] = bg;\n    }\n    return bg;\n}	0
16591626	16590662	Get Active Directory users by a list of guid	public List<UserPrincipal> FindAllUsers(List<Guid> allGuids)\n{\n   List<UserPrincipal> result = new List<UserPrincipal>();\n\n   // set up domain context\n   using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))\n   {\n       foreach(Guid userGuid in allGuids)\n       { \n          // find a user\n          UserPrincipal user = UserPrincipal.FindByIdentity(ctx, userGuid);\n\n          if(user != null)\n          {\n              result.Add(user);\n          }\n       }\n    }\n\n    return result;\n}	0
9498771	9498595	Getting DataList selected item in a text box	protected void DataList1_ItemCommand(object source, DataListCommandEventArgs e)\n        {\n            if (e.CommandName == "Select")\n            {\n                ((TextBox)e.Item.FindControl("Textboxname")).Text = ((Label)e.Item.FindControl("LabelName")).Text;\n            }\n        }	0
14939402	14937844	How to repair an excel file?	Missing missing = Missing.Value;\nApplication excel = new Application();\nWorkbook workbook = excel.Workbooks.Open(sourceFilePath,\n    missing, missing, missing, missing, missing,\n    missing, missing, missing, missing, missing,\n    missing, missing, missing, XlCorruptLoad.xlRepairFile);\nworkbook.SaveAs(savedFile, XlFileFormat.xlWorkbookDefault,\n    missing, missing, missing, missing,\n    XlSaveAsAccessMode.xlExclusive, missing,\n    missing, missing, missing, missing);\nworkbook.Close(true, missing, missing);	0
6543309	6543296	How to check for the current background color of a grid?	SolidColorBrush brush = LayoutRoot.Background as SolidColorBrush;\nif (brush != null) {\n    if (brush.Color == Colors.White) {\n        // Do something\n    }\n}	0
4573354	4573115	Custom grid LINQ to SQL	public partial class LinqGrid<T> : UserControl where T : class, new()\n{\n        System.Data.Linq.Table<T> tmpDataTable;\n        public LinqGrid()\n        {\n            InitializeComponent();\n        }\n        public void Bind(System.Data.Linq.Table<T> listSource)\n        {          \n            Project.dbClassesDataContext dbc = new Project.dbClassesDataContext();\n            tmpDataTable = listSource;\n            var query = (from c in listSource select c);\n            dgvRecords.DataSource = query.Take(10).ToList();\n        }\n        private void btnNext_Click(object sender, EventArgs e)\n        {\n            tmpDataTable.Skip(10).Take(10); ....\n        }\n   }	0
15714473	15346608	Cannot insert the value NULL into column 'UserId'	Guid userGuid = (Guid)Membership.GetUser(User.Identity.Name).ProviderUserKey;\n\nUserIdLabel.Text = userGuid.ToString();	0
2002421	2002407	Possible to do a union in LINQ?	var Result = setA.Union(setB)	0
22250523	22250439	C# regex to match a number in fourth line	Match match = Regex.Match(input, @"<th>Total enrolments</th>\s*<td>\s*(\d+)\s*</td>", RegexOptions.Multiline);\nif (match.Success)\n{\n    Console.WriteLine(match.Groups[1].Value);\n}	0
27703759	27703146	How do I center content in a Panel?	Panel panel = new Panel();\npanel.Size = new Size(300, 100);\npanel.Dock = DockStyle.Bottom;\n\nButton button = new Button();\nbutton.Size = new Size(70, 25);\nbutton.Location = new Point((panel.Width - button.Width) / 2, (panel.Height - button.Height) / 2);\nbutton.Anchor = AnchorStyles.None;\n\npanel.Controls.Add(button);\nthis.Controls.Add(panel);	0
2296558	2296533	Add value in listbox from list of values without using for loop	using System.Linq;\n...\n\nforeach (ClsPC pc in iclsobj.GetPC()) \n{     \n    if (listBox1.Items.Count == 0) \n    { \n        listBox1.Items.Add(pc.IPAddress); \n    } \n    else \n    { \n        if (!listBox1.Items.Any(i => String.Compare(i.ToString(), pc.IPAddress, true) == 0))\n        {\n           listBox1.Items.Add(pc.IPAddress); \n        }\n   } \n}	0
16519380	16387768	How to delete all users in my membership table?	var dbUsernames = context.Database.SqlQuery<string>("SELECT UserName FROM UserProfile");\nforeach (string dbUsername in dbUsernames)\n{\n    string[] userRoles = Roles.GetRolesForUser(dbUsername);\n    if (userRoles != null && userRoles.Length > 0)\n    {\n        Roles.RemoveUserFromRoles(dbUsername, userRoles); \n    }\n    int userId = context.Database.SqlQuery<int>("SELECT UserId FROM UserProfile WHERE UserName = {0}", dbUsername).First();\n    // HERE: Delete any other dependent rows in other tables that use UserId, and have referential integrity\n    // Now tear down any final bits and delete the user, for example: \n    Membership.DeleteUser(dbUsername, true);\n    context.Database.ExecuteSqlCommand(\n        "DELETE FROM webpages_Membership WHERE UserId = {0}", userId);\n}	0
33349849	33349476	Filter on ObservableCollection list using lambda expression	Queries.List = new ObservableCollection<Query>(Queries.List.Where(x => x.Name.Equals(value)));	0
29678150	29677960	How to generate control level events automatically in asp.net	protected void MyControlId_EventName(object sender, EventArgs e);	0
29713574	29709819	get an enum from ExecuteMethodCall()	public DbReturn spExample_upd(int id1)\n{\n    return (DbReturn)spExample_upd_internal(id1);\n}\n\n[Function(Name = "spExample_upd")]\nprivate int spExample_upd_internal([Parameter(Name = "Id1", DbType = "int")] int id1)\n{\n    var result = ExecuteMethodCall(this, (MethodInfo)MethodInfo.GetCurrentMethod(), id1);\n    return (int)result.ReturnValue;\n}	0
14348529	14330625	C# WindowsForms UserControl's Controls Designer Support	using System.Windows.Forms;\nusing System.Windows.Forms.Design;\n\n    public override void Initialize(IComponent component)\n    {\n        base.Initialize(component);\n\n        if (this.Control is MyUserControl)  // replace this with your usercontrol type\n        {\n            // cast this.Control to you type of usercontrol to get at it's\n            // controls easier\n            var i = this.Control as MyUserControl; // replace ***\n\n            this.EnableDesignMode(i.label1, "unique_name1");\n            this.EnableDesignMode(i.pictureBox1, "unique_name2");\n        }\n    }	0
6561776	6561554	Customize SqlDataSource to store part of string	protected void Buton_Click(object sender, EventArgs e)\n{\n        SqlDataSource1.UpdateParameters["pic"].DefaultValue = "string fetched from substring method";\n        SqlDataSource1.Update();\n}	0
13651917	13651757	How to use BinaryReader Read method to read dynamic data?	static object s_lock = new object();\nstatic IDictionary<Type, Func<BinaryReader, dynamic>> s_readers = null;\nstatic T ReadData<T>(string fileName)\n{\n    lock (s_lock)\n    {\n        if (s_readers == null)\n        {\n            s_readers = new Dictionary<Type, Func<BinaryReader, dynamic>>();\n            s_readers.Add(typeof(int), r => r.ReadInt32());\n            s_readers.Add(typeof(string), r => r.ReadString());\n            // Add more here\n        }\n    }\n\n    if (!s_readers.ContainsKey(typeof(T))) throw new ArgumentException("Invalid type");\n\n    using (var fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))\n    using (var reader = new BinaryReader(fs))\n    {\n        return s_readers[typeof(T)](reader);\n    }\n}	0
2048845	1200576	Find all controls on msform from c#	using System;\nusing Microsoft.Office.Interop.Excel\nusing VBA = Microsoft.Vbe.Interop;\n\n...\n\nVBA.Forms.UserForm form;\nVBA.Forms.Control c;\n\nforeach (VBA.VBComponent mod in wb.VBProject.VBComponents)\n{\n    // Use only VBA Forms\n    if (!(mod.Designer is VBA.Forms.UserForm)) continue;\n\n    form = (VBA.Forms.UserForm) mod.Designer;\n\n    for (int i = 1; i < form.Controls.Count; i++)\n    {\n        c = (VBA.Forms.Control)form.Controls.Item(i);\n        ...\n    }\n}	0
21469322	21469200	C# How to download a webpage or URI only if it is under size N?	void Main()\n{\n    const long PageSizeLimit = 1000000;\n    var url = "http://www.stackoverflow.com";\n    HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n    request.Method = "HEAD";\n    long pageSize;\n    string page;\n\n    using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())\n    {\n        pageSize = response.ContentLength;\n    }\n\n    // if content lenth is not present -> get full page\n    if (pageSize > 0 && pageSize < PageSizeLimit)\n    {\n        page = DownloadPage(url);\n        ProcessPage(page);\n    }\n    else\n    {\n        page = DownloadPage(url);\n\n        if (page.Length < PageSizeLimit)\n        {\n            ProcessPage(page);\n        }\n    }\n}\n\npublic string DownloadPage(string url)\n{\n    using (var webClient = new WebClient())\n    {           \n        return webClient.DownloadString(url);\n    }\n}\n\npublic void ProcessPage(string page)\n{\n    // do your processing\n}	0
12197956	12197893	Get objects from collection A where the ID of A exists in a collection of B objects	var q = Persons.Where(p => Countries.Any(c => p.Id== c.PersonId))	0
8295628	8249014	Fluent Nhibernate Mapping Relationships Across Schemas	class SiteMap : ClassMap<Site>\n{\n    public SiteMap()\n    {\n        Join("MySchema.Options", join =>\n        {\n            join.KeyColumn("SiteId");\n            join.Component(x => x.Options, c => c.Map(x => x.Prop1));\n        });\n    }\n}	0
448800	447943	How do i write a Regular Expression to match text containing XYZ but not ABC?	^(?:(?!ABC).)*XYZ	0
1702005	1701894	break a string in parts	var parts = s.Split(new[] { '|' }, StringSplitOptions.RemoveEmptyEntries);\n\nforeach (string word in parts)\n{\n  Console.WriteLine(word);\n}	0
6797855	6797777	Is a string property able to have a function?	public class person\n{\n  public string firstname { get;set;}\n  public string lastname { get;set;}\n\n  public person(string fname, string lname)\n  {\n    firstname = fname;\n    lastname = lname;\n  }\n\n  public string GetEmailRespPattern()\n  {\n    //split firstname, take what you want\n    //take what you want from last name.\n   // add extra information.\n   //concatenate and return it.\n  }\n}	0
20993973	20993877	How to Sort a Dictionary by key string length	class LengthComparer : IComparer<String>\n{\n    public int Compare(string x,string y)\n    {\n        int lengthComparison=x.Length.CompareTo(y.Length)\n        if(lengthComparison==0)\n        {\n           return x.CompareTo(y);\n        }\n        else\n        {\n           return lengthComparison;\n        }\n    }\n }	0
20428133	20427965	C#, after get value from textarea, how to split 2 strings and store in 2 separate arrays?	var ips = new List<string>();\nvar domains = new List<string>();\nforeach (var elements in txt.Text\n    .Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)\n    .Skip(1)\n    .Select(line => line.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries)))\n{\n    ips.Add(elements[0]);\n    domains.Add(elements[1]);\n}\nipsArray = ips.ToArray();\ndomainsArray = domains.ToArray();	0
2264910	2184275	How do I insert a row in to a Google spreadsheet using c#	public void AddToGoogle()\n    {\n        var client = new DatabaseClient(Settings.Default.GmailAccount, Settings.Default.GmailPassword);\n        string dbName = Settings.Default.WorkBook;\n\n        var db = client.GetDatabase(dbName) ?? client.CreateDatabase(dbName);\n        string tableName = Settings.Default.WorkSheet;\n\n        var t = db.GetTable<ActivityLog>(tableName) ?? db.CreateTable<ActivityLog>(tableName);\n        var all = t.FindAll();\n\n        t.Add(this);\n    }	0
10443859	9884414	How to read PDF bookmarks programmatically	PdfReader pdfReader = new PdfReader(filename);\n\nIList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(pdfReader);\n\nfor(int i=0;i<bookmarks.Count;i++)\n{\n    MessageBox.Show(bookmarks[i].Values.ToArray().GetValue(0).ToString());\n\n    if (bookmarks[i].Count > 3)\n    {\n        MessageBox.Show(bookmarks[i].ToList().Count.ToString());\n    }\n}	0
7713309	7713260	Disable button if boolean variable is true	if (formSubmitted)\n{\n    acceptButton.Enabled = false; \n    declineButton.Enabled = false;\n}	0
19271062	19270507	Correct way to use Random in multithread application	public static class StaticRandom\n{\n    static int seed = Environment.TickCount;\n\n    static readonly ThreadLocal<Random> random =\n        new ThreadLocal<Random>(() => new Random(Interlocked.Increment(ref seed)));\n\n    public static int Rand()\n    {\n        return random.Value.Next();\n    }\n}	0
11076333	11076307	WPF event for clicking textboxes in C#	private void yourTextBox_TextInput(object sender, TextCompositionEventArgs e)\n{  \n    if (e.Text == "K")\n    {\n    }\n}	0
29564529	29563543	DataGridView call CellFormatting only once	private void dgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)\n{\n    dgv.Rows[0].Cells[0].Style.BackColor = Color.Red;\n}	0
14506712	14506539	Loop through Excel worksheets and save text into a TXT file with C#	using (StreamWriter sw = File.CreateText("ExtractedText.txt"))\n{\n    var excelApp = new Excel.Application();\n    var workBook = excelApp.Workbooks.Open(thisFile);\n\n    foreach (var sheet in workBook.Worksheets)\n    {\n      foreach (var row in sheet.UsedRange.Rows)\n      {\n        foreach (var cell in row.Columns)\n        {\n          sw.Write(cell.Value + " ");\n        } \n        sw.WriteLine();\n      }\n    }\n}	0
15095854	15095632	ASP.NET Default page for particular user	protected void Login1_LoggedIn(object sender, EventArgs e)\n{\n    if (Login1.UserName == "YourUserName")\n        Login1.DestinationPageUrl = "YourDestinationPageUrl";\n}	0
919672	919645	How to delete node from XML file using C#	XmlDocument doc = new XmlDocument();\ndoc.Load(fileName);\nXmlNodeList nodes = doc.SelectNodes("//Setting[@name='File1']");	0
16995456	16995094	How to calculate SCREEN to WORLD position in 2D game	public Vector2 ScreenToWorld(Vector2 onScreen)\n    {\n        var matrix = Matrix.Invert(World.Camera.CurrentTransformation);\n        return Vector2.Transform(onScreen, matrix);\n    }	0
16547101	16545756	Validating inherited attribute using DataAnnotations	public class LibraryRequestViewModel  {\n     private LibraryRequest request;\n\n     public LibraryRequestViewModel(LibraryRequest request){\n          this.request = request;\n     }\n\n     [Required]\n     public string Password {\n         get { return this.request.Password; }\n         set { this.request.Password = value; }\n     }\n     // do this for all fields you need\n  }	0
29472	29436	Compact Framework - how do I dynamically create type with no default constructor?	MyObj o = null;\nAssembly a = Assembly.LoadFrom("my.dll");\nType t = a.GetType("type info here");\n\nConstructorInfo ctor = t.GetConstructor(new Type[] { typeof(string) });\nif(ctor != null)\n   o = ctor.Invoke(new object[] { s });	0
22719864	22641061	How to access nested key value pairs from an object in C#?	string root_str = ((ConverterCollections.AbstractConverterCacheEntry)         (cacheItem)).Key.ToString();\nstring parent_str = ((DictionaryEntry)(a)).Key.ToString();\nstring child_str = ((object[])(((DictionaryEntry)(a)).Value))[0].ToString();	0
20557746	20557098	Transactions with IsolationLevel Snapshot cannot be promoted	public static TransactionOptions GetTransactionOptions()\n{\n    TransactionOptions tranOpt = new TransactionOptions();\n    tranOpt.IsolationLevel = IsolationLevel.Serializable;\n    return tranOpt;\n}	0
6719212	6538293	Property set isnt being triggered with a UITypeEditor implemented	public override object EditValue(ITypeDescriptorContext context, System.IServiceProvider provider, object value)\n    {\n        IWindowsFormsEditorService service = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;\n        OptoSigmaLinearSettings opto = value as OptoSigmaLinearSettings;\n        opto = (OptoSigmaLinearSettings)value;\n\n        if (opto == null)\n        {\n            opto = new OptoSigmaLinearSettings();\n        }\n\n        if (service != null)\n        {\n            using (OptoSigmaLinearSetup form = new OptoSigmaLinearSetup(opto))\n            {\n                DialogResult result;\n                result = service.ShowDialog(form);\n\n                if (result == DialogResult.OK)\n                {\n                    opto = form.GeneralSettings;\n\n                }\n            }\n        }\n        return opto;\n    }	0
3724676	3724654	Replace a substring in each element of a string array?	arrayOfStrings = arrayOfStrings.Select(s => s.Replace("abc", "xyz")).ToArray();	0
10252867	10251397	MSChart X-Axis Dates	Series.IsXValueIndexed = true;	0
8714167	8704446	How to set Dependency Properties in a Control which inherits from an abstract UserControl?	Visibility="{Binding myPropertyRegistrationName, RelativeSource={RelativeSource FindAncestor, AncestorType=myNS:myType}}"	0
10276404	10275021	How can I detect when the DataGridView.RowValidating event is from a user interaction vs BindingSource list change?	private void dataGridView1_RowsAdded(object sender, \n    DataGridViewRowsAddedEventArgs e)\n{\n    if (dataGridView1.Rows[e.RowIndex].IsNewRow)\n    {\n        return;\n    }\n\n    dataGridView1[1, e.RowIndex].Value = \n        (dataGridView1.Rows[e.RowIndex].DataBoundItem as DomainModel).Name;\n}	0
31589134	31587883	After application has finished, why runtime values appear in design mode?	bool designMode = (LicenseManager.UsageMode == LicenseUsageMode.Designtime);	0
556213	539503	WCF: Individual methods or a generic ProcessMessage method accepting xml	// Just using fields for simplicity and no attributes shown.\ninterface WCFDataContract\n{\n    // Header details\n    public int id;\n    public int version;\n    public DateTime writeDateTime;\n\n    public string xmlBlob;\n\n    // Footer details\n    public int anotherBitOfInformation;\n    public string andSoemMoreInfo;\n    public book andABooleanJustInCase;\n\n}	0
25829091	25708655	C# Sending data via Serial Port, data in byte array is received incomplete	bytenumber = port.Read(data, 0, 10);\n\n        if (data[0] == 0xFF)\n        {\n        }\n    }	0
20483892	20483715	Can't find the correct regex pattern to get value between html tags	HtmlDocument doc = new HtmlWeb().Load(String.Format("http://sitecontainingspan.com"));\n\nvar value = doc.DocumentNode.SelectSingleNode("//span[@class='market_listing_price market_listing_price_with_fee']").InnerText;	0
5248683	5248454	Can i use VS2010 PrivateObject to access a static field inside a static class?	string propertyName = "bar";\nFieldInfo fieldInfo = typeof(foo).GetField(propertyName, BindingFlags.NonPublic | BindingFlags.Static);\nobject fieldValue = fieldInfo.GetValue(null);	0
887773	887734	How do I convert a string into an OctetString (C#)?	byte[] octets = System.Text.Encoding.ASCII.GetBytes("abcd");	0
30106771	30078728	Implementing jaccard similarity in c#	var CommonNumbers = from a in A.AsEnumerable<double>()\n                    join b in B.AsEnumerable<double>() on a equals b\n                    select a;\ndouble JaccardIndex = (((double) CommonNumbers.Count()) /\n                       ((double) (A.Count() + B.Count())));	0
39091	33250	Caching Active Directory Data	System.DirectoryServices.DirectoryEntry entry = new System.DirectoryServices.DirectoryEntry();               \n\n// Push the property values from AD back to cache.\n\nentry.RefreshCache(new string[] {"cn", "www" });	0
27385624	27385400	Run cmd command from inside my application	var psi = new ProcessStartInfo(@"wmic");\npsi.Arguments = @"baseboard get product,manufacturer";\npsi.WindowStyle = ProcessWindowStyle.Hidden;\npsi.UseShellExecute = false;\npsi.RedirectStandardOutput = true;\n\nstring val = String.Empty;\n\nvar p = Process.Start(psi);\np.BeginOutputReadLine();\np.OutputDataReceived += delegate(object sender, DataReceivedEventArgs eventArgs)\n{\n    val += eventArgs.Data + "\r\n";\n};\np.WaitForExit();\n\nMessageBox.Show(val); // Start parsing it here	0
25175364	25175335	Load a Type from Assembly using simple class name	var types = assembly.GetTypes().Where(type => type.Name == "MyClass");\nvar firstType = types.FirstOrDefault();	0
22131795	22131683	Generate unique number from Button Click	CREATE TABLE dbo.Orders\n(\n    OrderID into IDENTITY(1,1),\n    -- other columns\n)	0
26018818	26018675	Add object to a BindingList in a BindingList	// Get the activity from bindingListActivity, whose k._dataGridViewId is equal to 1.\nvar activity = bindingListActivty.SingleOrDefault(k => k._dataGridViewId == 1);\n\n// If the activity has been found and the a new BuyOrders object.\nif(activity!=null)\n    activity.addBuyOrders(new BuyOrders());	0
15220464	14833078	Why does removing a local group via WinNT protocol results in a NotImplementedException?	void RemoveGroup(string groupName)\n{\n    string path = string.Format("WinNT://domain/myServer/{0}", groupName);\n    using (DirectoryEntry entry = new DirectoryEntry(path, @"domain\serviceAccount", @"********"))\n    {\n        using (DirectoryEntry parent = rootEntry.Parent)\n        {\n            parent.Children.Remove(entry);\n        }\n    }\n}	0
28957777	28926579	nested json by using stored procedure call	//Declare the object for return (if any)\nStudent objWorkingObject = new Student();\n\n//Populate into XML\nXmlDocument _Doc = new XmlDocument();\n_Doc.LoadXml(strOrigObject);\nvar ser = new System.Xml.Serialization.XmlSerializer(typeof(Student));\nobjWorkingObject = (Student)ser.Deserialize(new XmlNodeReader(_Doc.DocumentElement));	0
3573542	3573509	How to trim the illegal characters from a string	string str = string.Join(string.Empty, File.ReadAllLines(FileName));	0
17855530	17855034	Display a contact using storagekind.phone	Account Accounttype = new Account();\nStorageKind strgKind = StorageKind.Phone;\n\nAccounttype.Kind = strgKind;	0
4709392	4709369	How to declare a inline object with inline variables without a parent class	object[] x = new object[2];\n\nx[0] = new { firstName = "john", lastName = "walter" };\nx[1] = new { brand = "BMW" };	0
11885574	11767748	How do I follow a Javascript Link without onClick	foreach (HtmlElement i in webBrowser1.Document.All)\n    {\n        if (i.OuterText == "CSV Text File" && i.GetAttribute("href") != "")\n        {\n            webBrowser1.Navigate(i.GetAttribute("href"));\n        }\n    }	0
12973142	12973037	C# Need a little assistance with HttpWebRequest Post data	string targetUrl = "http://www.url.url";\n\n        var postBytes = Encoding.Default.GetBytes(@"authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D&question%5Bquestion_text%5D=TEST+TEST+TEST&authenticity_token=pkhn7pwt3QATOpOAfBERZ%2BRIJ7oBEqGFpnF0Ir4RtJg%3D");\n\n        var httpRequest = (HttpWebRequest)WebRequest.Create(targetUrl);\n\n        httpRequest.ContentLength = postBytes.Length;\n        httpRequest.Method = "POST";\n\n        using (var requestStream = httpRequest.GetRequestStream())\n            requestStream.Write(postBytes, 0, postBytes.Length);\n\n        var httpResponse = httpRequest.GetResponse();\n\n        using (var responseStream = httpResponse.GetResponseStream())\n            if (responseStream != null)\n                using (var responseStreamReader = new StreamReader(responseStream))\n                {\n                    var serverResponse = responseStreamReader.ReadToEnd();\n                }	0
27977936	27977892	Add more than one tables in RDLC	ReportDataSource rds = new ReportDataSource("dsChart",ObjectDataSource1);\n\nReportDataSource rds2 = new ReportDataSource("DataSet1",ObjectDataSource2);\n\nrptViewer.LocalReport.DataSources.Clear();\n\nrptViewer.LocalReport.DataSources.Add(rds);\n\nrptViewer.LocalReport.DataSources.Add(rds2);	0
33937842	33936646	Get text inside of a span	var rigaStagioneSerie = document.DocumentNode.SelectNodes("//td[@class='rigaStagioneSerie']");\nList<string> pageTitles = new List<string>();\n\nforeach (var title in rigaStagioneSerie)\n{\n    if (title.ChildNodes.Count == 1)\n    {\n        pageTitles.Add(title.InnerText.Replace("\n", string.Empty).Replace("\t", string.Empty));\n    }\n\n}\n\nvar titoloSerie = document.DocumentNode.SelectNodes("//span[@class='titoloSerie']");\n\nforeach (var title in titoloSerie)\n{\n    pageTitles.Add(title.InnerText);\n}	0
28584419	28583652	Get body of Expression<Func<T>>	private void AddItemsToCollectionAndInvokePropertyChanged<T,U>(Expression<Func<U>> propertyNameExpression, IList<T> addItems)\n{\n    var p = (PropertyInfo)((MemberExpression)propertyNameExpression.Body).Member;\n    var c = (ExtendedObservableCollection<T>)p.GetValue(this, null);\n    c.AddItems(addItems);\n    OnPropertyChanged(propertyNameExpression);\n}	0
15270578	15270511	How to load the DateTimePicker with ShowCheckBox unchecked	DateTimePicker dateTimePicker1 = new DateTimePicker();\ndateTimePicker1.ShowCheckBox = true;\ndateTimePicker1.Checked= false;	0
3857517	3857444	C#: How do I get the ID number of the last row inserted using Informix	Insert(String query)\n{\n   Execute the Sql Query: query\n   result = Execute the Sql Query: "SELECT last_insert_id"\n   return the first element of result\n}	0
3678159	3678131	Sorting Lists with sub items in C#	List<MyOrder> sortedList = myOrders\n    .OrderBy(myOrder => myOrder.OrderItems.Min(myItem => myItem.ItemCreateDate))\n    .ToList();	0
12811440	12811395	How to dispose a WPF application GUI?	this.Close(); //Will close the window but keep the application running.\n\nvar mw = new MainWindow();\nmw.Show(); //Will open a new MainWindow and show it.\nmw.Close(); //Close this one too.	0
30126729	30106408	Web Api Parameter binding Inconsistent	json.SerializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.Objects;	0
8535253	8535151	c# Exchange Webservices delete appointment in public folder	deleteAppointmennt.Delete(DeleteMode.SoftDelete, SendCancellationsMode.SendToNone);	0
16050375	15562088	C# Wpf toolkit autocomplebox - how to get the selected item?	SelectedItem="{Binding ElementName=this,\n           Path=ProductID,\n           Mode=TwoWay,\n           UpdateSourceTrigger=LostFocus}"	0
2201648	2201595	C# - Simplest way to remove first occurance of a substring from another string	int index = sourceString.IndexOf(removeString);\nstring cleanPath = (index < 0)\n    ? sourceString\n    : sourceString.Remove(index, removeString.Length);	0
17130377	17085493	Link ms word hyperlink to a place in the document	Microsoft.Office.Interop.Word.Paragraph oPara2;\n        object oRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;\n        oPara2 = oDoc.Content.Paragraphs.Add(ref oRng);\n        oPara2.Range.Text = "Heading 2";\n        oPara2.Format.SpaceAfter = 6;\n        oPara2.Range.InsertParagraphAfter();\n        oDoc.Bookmarks.Add("BookmakrName3", oRng);\n\n\n        object oAddress = "#BookmakrName3";\n\n        //Add text after the chart.\n        wrdRng = oDoc.Bookmarks.get_Item(ref oEndOfDoc).Range;\n        wrdRng.InsertParagraphAfter();\n        wrdRng.InsertAfter("Click here to jump");\n        wrdRng.Hyperlinks.Add(wrdRng, ref oAddress);	0
25765807	25765529	How to access an Excel WorkSheet cell in c#	using Microsoft.Office.Interop.Excel;\nusing Application = Microsoft.Office.Interop.Excel.Application;\nusing Excel = Microsoft.Office.Interop.Excel;\n\nApplication excelApplication = new Excel.Application\n{\n    Visible = true,\n    ScreenUpdating = true\n};\n\n_Workbook workbook = excelApplication.Workbooks.Open(@"C:\Temp\Book1.xlsx");\n_Worksheet sheet = workbook.Worksheets[1];\nRange range = sheet.Range["B1"];\nrange.Formula = "Test";\n\nexcelApplication.Quit();	0
13755370	13341017	Reading a spritesheet XML file in XNA	Stream stream = TitleContainer.OpenStream("Content\\" + fileName + ".xml");\nXDocument doc = XDocument.Load(stream);	0
4156107	4150012	How to draw something (line, circle etc.) on a Gtk# Window?	using (Cairo.Context g = CairoHelper.Create (myWindow.GdkWindow)) {\n    g.MoveTo (0, 0);\n    g.LineTo (10, 10);\n    g.Color = new Color (1, 1, 1);\n    g.Stroke ();\n}	0
8718213	8718199	Passing a 'Type' to a Generic Constructor	Type gt = typeof(ManagedThread<>).MakeGenericType(ThreadType);\nobject t = Activator.CreateInstance(gt, this,this.GetConfiguration(ThreadType));	0
18401092	18400956	Best way to store serialization related info between serialization and deserialization	var settings = new JsonSerializerSettings() { \n                     TypeNameHandling = TypeNameHandling.All };\n\nvar json = JsonConvert.SerializeObject(obj, settings);\nvar newObj = JsonConvert.DeserializeObject<SomeType>(json, settings);	0
13803040	13803030	Removing Last Comma	var result = query.TrimEnd(',', ' ', '\n');	0
11041704	11041652	download unknown file from Url	extension/mime-type	0
16641419	16641243	ASP.NET ObjectDataSource could not find a non-generic method that has parameters	[DataObjectMethod(DataObjectMethodType.Update)]\npublic static void UpdateAnimeList(string name, string **animeImage**, string synopsis, \n    string type, short episodes, string genres, decimal rating, int original_animeID,\nint animeID) {\n    ...\n}	0
22712007	22706663	how to send file from action to other action using session or tempdata in mvc	[HttpPost]\npublic ActionResult Index(HttpPostedFileBase fil)\n{\n    if (fil != null && fil.ContentLength > 0)\n    {\n        // Read bytes from http input stream\n        BinaryReader b = new BinaryReader(file.InputStream);\n        byte[] binData = b.ReadBytes(file.InputStream.Length);\n        string result = System.Text.Encoding.UTF8.GetString(binData);\n        Session["doc2"] = result;\n\n    }\n    return RedirectToAction("Xmlview");\n}\n\n[HttpGet]\npublic ActionResult Xmlview()\n{\n    Value model2 = new Value();\n    string strall = "";\n    string content = Session["doc2"].ToString();\n    if (!String.IsNullOrEmpty(content))\n    {\n        XDocument xml = XDocument.Parse(content);  \n        var allElements = xml.Elements();\n    }\n}	0
1919018	1919003	Clearing a StringBuilder Object's Current String	stringBuilderObject.Remove(0, stringBuilderObject.Length)	0
4432573	4403756	learning monodevelop and am having trouble getting a messgae box to appear	void ShowMessage (Window parent, string title, string message)\n{\n    Dialog dialog = null;\n    try {\n        dialog = new Dialog (title, parent,\n            DialogFlags.DestroyWithParent | DialogFlags.Modal,\n            ResponseType.Ok);\n        dialog.VBox.Add (new Label (message));\n        dialog.ShowAll ();\n\n        dialog.Run ();\n    } finally {\n        if (dialog != null)\n            dialog.Destroy ();\n    }\n}	0
12740467	12740185	Read XML File with variable tags	XmlDocument xDoc = new XmlDocument();\nxDoc.Load("Server.MapPath("~/XMLFile.xml")");\n\nXmlNodeList nodeList;\nnodeList = xDoc.DocumentElement.SelectNodes("Employee");\n\nforeach (XmlNode emp in nodeList)\n{\n    foreach (XmlNode child in emp.ChildNodes)\n    {\n        Response.Write(child.LocalName);\n        Response.Write(":");\n        Response.Write(child.InnerText);\n        Response.Write("\n");\n    }\n\n}	0
25336001	25335871	Advanced Search Like with LINQ	void Main()\n{\n    var queryInfo = new DomainQuery();\n    var ContentList = new List<Content>();\n\n    var query = ContentList\n        .Where(q=>queryInfo.PhrasesIncludeAny\n            .Any(item=>q.Summary.Any(subitem=>subitem == item)))\n        .Where(q=>queryInfo.PhrasesIncludeAll\n            .All(item=>q.Summary.All(subitem=>subitem == item)))\n        .Where(q=>!queryInfo.PhrasesIncludeAll\n            .All(item=>q.Summary.All(subitem=>subitem == item)))\n        .Where(q=>q.CreatedDate < queryInfo.CreatedBefore)\n        .Where(q=>q.CreatedDate > queryInfo.CreatedAfter);\n\n}	0
13443650	13443590	winform Close self plus another WebBrowserControl	this.Load += (sender,args)=>{ /*do all your work here*/  \n     string extractededVal = Iengn.ExtractPageValue(Iengn.itrfWebEng);\n     string flnm = @" the directory path to file --> \dolarRate.asp";\n     File.WriteAllText(fn, extractededVal);\n     Application.Exit(); \n  };	0
21411689	21411443	C# WPF -- Mouse click spawning shape from the center of the click	Canvas.SetLeft(Rendershape, e.GetPosition(canvasArea).X - ( Rendershape.Width / 2.0 ) );\nCanvas.SetTop(Rendershape, e.GetPosition(canvasArea).Y - ( Rendershape.Height / 2.0 ) );	0
4909310	4908715	C# double to real	static byte[] DoubleToReal48(double d)\n{\n    byte[] r = new byte[6];\n\n    long bits = BitConverter.DoubleToInt64Bits(d);\n    bool negative = ((bits >> 63) & 1) != 0;\n    long exponent = ((bits >> 52) & 0x7FF) - 1023;\n    long mantissa = bits & 0xFFFFFFFFFFFFFL;\n\n    long raw = (negative ? 1 : 0);\n    raw = (raw << 39) | (mantissa >> 13);\n    raw = (raw << 8) | ((exponent + 129) & 0xFF);\n\n    for (int k = 0; k < 6; k++)\n    {\n        r[k] = (byte)(raw & 0xFF);\n        raw >>= 8;\n    }\n    return r;\n}\n\nstatic double Real48ToDouble(byte[] r)\n{\n    long raw = 0;\n    for (int k = 5; k >= 0; k--)\n    {\n        raw = (raw << 8) | r[k];\n    }\n\n    long mantissa = (raw << 5) & 0xFFFFFFFFFD000L;\n    long exponent = (((raw & 0xFF) - 129 + 1023) & 0x7FF) << 52;\n    long sign = (((raw & ~0x7FFFFFFFFFFFL) != 0) ? 1 : 0) << 63;\n\n    return BitConverter.Int64BitsToDouble(sign | exponent | mantissa);\n}	0
33247774	33246277	How to get TransactionScope to work on large sql transactions?	machine.config	0
5332297	5332213	How to bind to 2 different members in a class in WPF?	{Binding RelativeSource={RelativeSource Mode=FindAncestor, AncestorType=ListView}, Path=DataContext.HasPermissions}	0
11853253	11852977	How to View UploadValues Post Call Including Headers Being Sent	string userAgent = "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.1; WOW64; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; InfoPath.3; .NET4.0C; .NET4.0E; MS-RTC LM 8)";\n\nclient.Headers[HttpRequestHeader.UserAgent] = userAgent;	0
28347525	28336992	RequiredIf Conditional Validation for two variables in MVC4	[Required]\npublic bool Saturday{ get; set; }\n\n[Required]\npublic bool Sunday{ get; set; }\n\n[NotMapped]\npublic bool SatSun\n{\n    get\n    {\n        return (!this.Saturday && !this.Sunday);\n    }\n}\n\n[RequiredIf("SatSun",true)]\npublic string Holiday{ get; set; }	0
203962	203930	C# streaming sockets, how to separate messages?	byte[] data = ...\n  int len = data.Length;\n  byte[] prefix = Bitconverter.GetBytes(len);\n  stream.Write(prefix, 0, prefix.Length); // fixed 4 bytes\n  stream.Write(data, 0, data.Length);	0
21982008	21981850	How to use Eval function in the query string in a databind control like list view	NavigateUrl='<%# "Rep_calc.aspx?year=" + Eval("bal")%>'	0
827677	827672	How do I marshal a structure as a pointer to a structure?	[DllImport("MockVadavLib.dll", CharSet = CharSet.Ansi)]\npublic static extern IntPtr TheFunction(ref UserRec userRec);	0
14800236	14793428	Maximising borderless form covers task bar only when maximised from a normal size	private void ToggleStateButton_Click(object sender, EventArgs e) {\n        if (this.FormBorderStyle == FormBorderStyle.None) {\n            this.FormBorderStyle = FormBorderStyle.Sizable;\n            this.WindowState = FormWindowState.Normal;\n        }\n        else {\n            this.FormBorderStyle = FormBorderStyle.None;\n            if (this.WindowState == FormWindowState.Maximized) this.WindowState = FormWindowState.Normal;\n            this.WindowState = FormWindowState.Maximized;\n        }\n    }	0
17861987	17861778	Send data using threads	new Thread(() => BattleArena.ArenaGame(12)).Start();	0
22861749	22861451	Sharing app.config	// Create a Subkey\nRegistryKey newKey = Registry.CurrentUser.CreateSubKey("SOFTWARE\\SuperSoft\\App");\n\n// Write Values to the Subkey\nnewKey.SetValue("Value1", "Content1");\nnewKey.SetValue("Value2", "Content2");\n\n// read Values from the Subkey\nif (SubKeyExist("SOFTWARE\\SuperSoft\\App"))\n{\n  RegistryKey myKey = Registry.CurrentUser.OpenSubKey("SOFTWARE\\SuperSoft\\App");\n  string firstApp = (string)myKey.GetValue("Value1");\n  string secondApp = (string)myKey.GetValue("Value2");\n}	0
3776063	3776044	Ques regarding sending email to a specific user	var message = new MailMessage("abc@somedomain.com", "administrator@anotherdomain.com");\nmessage.Subject = "Testing";\nmessage.IsBodyHtml = true;\nmessage.Body = "<html><body><div>Test message</div><a href=\"http://www.google.com\">some link</a></body></html>";	0
2378618	2378592	Is there a Numeric Format String for the following?	x.ToString("+#;-#;+0")	0
23397131	23397010	Casting value-type constants	IL_000a:  ldc.r4     69.	0
30329273	30266945	How to format cells in Aspose	Workbook workBook = new Workbook();\n\nWorksheet workSheetIntroduction = workBook.Worksheets[0];\n\n\n//This Style object will make the fill color Red and font Bold\n\nStyle boldStyle = workBook.CreateStyle();\n\nboldStyle.ForegroundColor = Color.Red;\n\nboldStyle.Pattern = BackgroundType.Solid;\n\nboldStyle.Font.IsBold = true;\n\n\n//Bold style flag options\n\nStyleFlag boldStyleFlag = new StyleFlag();\n\nboldStyleFlag.HorizontalAlignment = true;\n\nboldStyleFlag.FontBold = true;\n\n\n//Apply this style to row 1\n\nRow row1 = workBook.Worksheets[0].Cells.Rows[0];\n\nrow1.ApplyStyle(boldStyle, boldStyleFlag);\n\n\n\n//Now set the style of indvidual cell\n\nCell c = workSheetIntroduction.Cells["B1"];\n\n\nStyle s = c.GetStyle();\n\ns.ForegroundColor = Color.Red;\n\ns.Pattern = BackgroundType.Solid;\n\ns.Font.IsBold = true;\n\nc.SetStyle(s);\n\n\n//Save the workbook\n\nworkBook.Save("output.xlsx");	0
6086340	6086185	Export to Excel, and change Sheet name	ExcelWorksheet worksheet = xlPackage.Workbook.Worksheets.Add("Tinned Goods");	0
32087640	32087448	Inserting a file into the project - trying to eliminate OpenFileDialog	string fileName = "YourDocument.doc";\nstring path = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, fileName);	0
20145885	20145713	Adding a css class to server control using extension method	public static void AddClass(this WebControl control, string newClass)\n{\n    if(!string.IsNullOrEmpty(control.CssClass))\n    {\n         control.CssClass += " " + newClass;\n    }\n    else\n    {\n       control.CssClass = newClass;\n    }\n}	0
4037491	4015534	Possible to pre-empt the Windows message loop?	private void btnCancel_Click(object sender, System.Windows.RoutedEventArgs e)\n        {\n            Dispatcher.Invoke(new Action(() => btnCancel.Command.Execute(null)), DispatcherPriority.Send);\n        }	0
11210544	11209797	fastest way to get n lowest from array	int samplesCount = samples.Count;\n\nfor (int j = numLowestSamples; j < samplesCount; j++)\n{\n    double sample = samples[j];\n\n    if (sample > 0 && sample < currentMax)\n    {\n        int k;\n\n        for (k = 0; k < numLowestSamples; k++)\n        {\n           if (sample < lowestSamples[k])\n           {\n              Array.Copy(lowestSamples, k, lowestSamples, k + 1, numLowestSamples - k - 1);\n              lowestSamples[k] = sample;\n\n              break;\n           }\n        }\n\n        if (k == numLowestSamples)\n        {\n           lowestSamples[numLowestSamples - 1] = sample;\n        }\n\n        currentMax = lowestSamples[numLowestSamples - 1];\n    }\n}	0
31583739	31581770	c# xml to csv api results	var orders =  orderResponse\n                  .Select(order => order.SomeProperty && ..)\norders.ToCsv().Print();	0
6422758	5959095	How to change HttpRuntime settings (eg WaitChangeNotification) at runtime?	// Turn the read only field non-readonly\nWebServicesSection wss = WebServicesSection.Current;\nSoapExtensionTypeElement e = new SoapExtensionTypeElement(typeof (TraceExtension), 1, PriorityGroup.High);\n\nFieldInfo readOnlyField = typeof(System.Configuration.ConfigurationElementCollection).GetField("bReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);\nreadOnlyField.SetValue(wss.SoapExtensionTypes, false);\n\n// Bind to web services section of config\nwss.SoapExtensionTypes.Add(e);\n\n// Restore the original so other things don't break\nMethodInfo resetMethod = typeof(System.Configuration.ConfigurationElementCollection).GetMethod("ResetModified", BindingFlags.NonPublic | BindingFlags.Instance);\nresetMethod.Invoke(wss.SoapExtensionTypes, null);\n\nMethodInfo setReadOnlyMethod = typeof(System.Configuration.ConfigurationElementCollection).GetMethod("SetReadOnly", BindingFlags.NonPublic | BindingFlags.Instance);\nsetReadOnlyMethod.Invoke(wss.SoapExtensionTypes, null);	0
4591591	4591368	Showing ClickOnce deployment version on WPF application	System.Deployment	0
27632359	27624844	Is there a way to cancel Touches on Awake of a Screen?	using UnityEngine;\nusing System.Collections;\n\npublic class ExampleClass : MonoBehaviour {\n\n    private bool newTouchesInThisScene = false;\n\n    void Update() {\n        for(int i = 0; i < Input.touchCount; ++i) {\n            if (Input.GetTouch(i).phase == TouchPhase.Began) {\n                newTouchesInThisScene = true;\n            }\n        }\n    }\n}	0
5804412	5804255	how to get parent node index when parent node is inserted at runtime in treelist?	TreeListNode parentNode = treeList1.AppendNode(..., null);\n    TreeListNode childNode = treeList1.AppendNode(..., parentNode);	0
11304472	11304399	Sorting data based on portion of the word	var sortedWords = words.Where(x => x.Contains("comp"))\n                       .OrderByDescending(x => x);	0
25417355	25416859	Infragistics Populate DropDown menu	Panel panel = new Panel();\n    panel.Controls.Add(new Button() { Text = "Button 1" });\n    panel.Controls.Add(new Button() { Text = "Button 2" });\n\n    UltraPopupControlContainer container = new UltraPopupControlContainer();\n    container.PopupControl = panel;\n\n    ultraDropDownButton1.PopupItem = container;	0
8277440	8277169	How to plot graph in windows form using Zedgraph library?	myGraph.AxisChange()	0
19246810	19246069	Sending an array as part of a PUT method in C#	client.AddParameter("imageData[]", data1);\nclient.AddParameter("imageData[]", data2);	0
3127317	3127251	How to learn transaction in EF or LINQ to SQL?	// use nested using block to decrease the indent\nusing (var ctx = new DataClassesCallCenterDataContext())\nusing (var scope = new TransactionScope())\n{\n    var test =\n        from c in ctx.sp_CallCenterAnketEntity()\n        select c;\n\n    // if you're sure that query result will have at least one record.\n    // else an exception will occur. use FirstOrDefault() if not sure.\n    // and why int? - is it the type of ID. Isn't int the type?\n    int? ID = test.First().ID; \n\n    // here you can use object initializer\n    var question = new QuestionsYesNo\n    {\n        Question = "Test3?",\n        Date = DateTime.Now\n    };\n\n    ctx.QuestionsYesNos.InsertOnSubmit(question);\n    ctx.SubmitChanges();\n\n    Rehber rehber = (\n        from r in ctx.Rehbers\n        where r.ID == ID\n        select r).First(); // again about being sure and FirstOrDefault\n\n    rehber.Name = @"SQL Server 2005'i bir [many more characters] izleyin.";\n\n    ctx.SubmitChanges();    \n    scope.Complete();\n}	0
12351007	12350936	How to add new Items to an Existing List c#?	foreach (var item in data)\n   {\n     QuestionMaster temp = new QuestionMaster();\n\n   }	0
17445587	17444786	Out string parameter C#	public static int ExecuteNonQuery(ref DbCommand command, out string ErrorMessage)	0
7409910	7409894	Show result on screen in each FOR loop?	public partial class Form1 : Form\n{\n    BackgroundWorker _worker;\n    public Form1()\n    {\n        InitializeComponent();\n        _worker = new BackgroundWorker();\n        _worker.WorkerReportsProgress = true;\n        _worker.DoWork += _worker_DoWork;\n        _worker.ProgressChanged += _worker_ProgressChanged;\n    }\n\n    private void _worker_ProgressChanged( object sender, ProgressChangedEventArgs e )\n    {\n        label1.Text = e.UserState.ToString();\n    }\n\n    private void _worker_DoWork( object sender, DoWorkEventArgs e )\n    {\n        for( int i = 0; i < 100; ++i )\n        {\n            _worker.ReportProgress( i, i );\n            // allow some time between each update,\n            // for demonstration purposes only.\n            System.Threading.Thread.Sleep( 15 );\n        }\n    }   \n\n    private void button1_Click( object sender, EventArgs e )\n    {\n        _worker.RunWorkerAsync();\n    }\n}	0
3784201	3784107	How do I unit test protected properties meant to be set only by NHibernate?	var mock = new Mock<IRepository>();\nvar mockStore = new Mock<Store>();\nmock.Setup(x => x.GetById<Store>(It.IsAny<int>())).Returns(mockStore.Object);\n\nmockStore.SetupGet(s => s.Id).Returns(5);\nmockStore.SetupGet(s => s.Value).Returns("Walmart");\n\nvar store = Repository.GetById<Store>(5);\nAssert.That(store.Id == 5);	0
23298324	23298072	How to find a leaf in a hierachy of Windows Forms?	for (int i = topLevelForm.OwnedForms.Length - 1; i >= 0; --i) {\n  topLevelForm.OwnedForms[i].Dispose();\n}	0
14621687	14621451	How to get MethodInfo of interface, if i have MethodInfo of inherited class type?	var methodParameterTypes = classMethod.GetParameters().Select(p => p.ParameterType).ToArray();\nMethodInfo interfaceMethodInfo = interfaceType.GetMethod(classMethod.Name, methodParameterTypes);	0
3397366	3397350	How to modify a nullable type's value?	public partial class L2SEntity {\n    public void Scale(double d) {\n        if (this.Amount.HasValue) {\n            this.Amount *= d;\n        }\n    }\n}	0
14608126	14607844	How to throw exception in Web API?	if (test == null)\n    {\n         throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.NotFound, \n"this item does not exist");\n    }	0
33673725	33673080	Index Of Longest Run C#	int IndexOfLongestRun(string input)\n{\n    int bestIndex = 0, bestScore = 0, currIndex = 0;\n    for (var i = 0; i < input.Length; ++i)\n    {\n        if (input[i] == input[currIndex])\n        {\n            if (bestScore < i - currIndex) \n            {\n                bestIndex = currIndex;\n                bestScore = i - currIndex;\n            }\n        }\n        else\n        {\n            currIndex = i;\n        }\n    }\n    return bestIndex;\n}	0
27184426	27182245	How to Create Tables in a SQL Server CE database file using C# code	var scripts = TableCreationScript\n    .Trim()\n    .Replace("create", "#create")\n    .Split(new []{'#'}, StringSplitOptions.RemoveEmptyEntries);\n\nfor each (var script in scripts)\n{\n    SqlCeCommand cmd = new SqlCeCommand(script);\n    cmd.Connection = connection;\n    cmd.ExecuteNonQuery();\n}	0
26434488	26434458	How to print the contents of an array to a label in c#	lblAnswer3.Text = string.Join(", ", number);	0
33407305	33407205	How to remove guid from file name when creating zip file?	var orgFileName = "1250a2d5-cd40-4bcc-a979-9d6f2cd62b9fLog.txt";\n  var newFileName = orgFileName.Substring (36);\n  File.Copy (orgFileName, newFileName, true);\n  zip.AddFile (newFileName);	0
12841235	12840839	find the center point of coordinate 2d array c#	List<Point> dots = new List<Point>();\nint totalX = 0, totalY = 0;\nforeach (Point p in dots)\n{\n    totalX += p.X;\n    totalY += p.Y;\n}\nint centerX = totalX / dots.Count;\nint centerY = totalY / dots.Count;	0
2746454	2713870	Implementing IXmlSerializable on a generated class that has XmlTypeAttribute	private bool mblnFlag;\n\npublic String Flag \n{\n   get\n   {\n      return mblnFlag;\n   }\n   set\n   {\n      mblnFlag = (value == "1")\n   }\n}	0
1234186	1233103	How to Determine the Sort Order of an NHibernate ICriteria Object?	var impl = session.CreateCriteria<User>().AddOrder(Order.Asc("Id")) as CriteriaImpl;\n\nforeach (CriteriaImpl.OrderEntry entry in impl.IterateOrderings())\n{\nOrder order = entry.Order;\n    // now you have the order and you can either parse it : "propertyName asc" \n                                                         or "propertyName desc"\n    // or you can check it out in debug, it has a few protected fields that you could reflect. \n    // not sure if there's another way.\n}	0
17760969	17760689	Using a Switch statement with Enum C#	using System.Globalization;\nstatic void Main(string[] args)\n{\n    Console.Write("Enter a Number to find out what Month it is: ");\n\n    int userInput = Convert.ToInt16(Console.ReadLine());\n    if(userInput > 0 && userInput < 13)\n    {            \n         string monthName = CultureInfo.CurrentCulture.DayTimeFormat.MonthNames[userInput-1];\n         int daysInMonth = DateTime.DaysInMonth(2013, userInput);\n         ......\n\n    }\n}	0
11696363	11696130	Can I get the standard currency format to use a negative sign instead of parentheses?	protected void Application_BeginRequest()\n{\n    var ci = CultureInfo.GetCultureInfo("en-US");\n\n    if (Thread.CurrentThread.CurrentCulture.DisplayName == ci.DisplayName)\n    {\n        ci = CultureInfo.CreateSpecificCulture("en-US");\n        ci.NumberFormat.CurrencyNegativePattern = 1;\n        Thread.CurrentThread.CurrentCulture = ci;\n        Thread.CurrentThread.CurrentUICulture = ci;\n    }\n}	0
6683719	6683675	Getting the decimals in a double variable in a culture sensitive way	private string GetDecimalDigits(double d, int digitsCount)\n{\n    double substracted = d - Math.Floor(d);\n    return Math.Round(substracted * Math.Pow(10, digitsCount)).ToString();\n}\n\nstring result = GetDecimalDigits(59.123, 2);	0
3334819	3334555	How to get the highlighted element only from a WPF combobox?(C# 3.0)	var editableTextBox = cmbExpressions.Template.FindName("PART_EditableTextBox", cmbExpressions) as TextBox;\nif (editableTextBox != null)\n{\n    var text = editableTextBox.SelectedText;\n}	0
6386101	6382583	Use credentials to interact with the Client Object Model of Sharepoint?	using System.Net;\nusing Microsoft.SharePoint.Client;\n\nusing (ClientContext context = new ClientContext("http://yourserver/")) {\n    context.Credentials = new NetworkCredential("user", "password", "domain");\n    List list = context.Web.Lists.GetByTitle("Some List");\n    context.ExecuteQuery();\n\n    // Now update the list.\n}	0
10712917	10711302	How to start with clearcanvas in .NET	string filename = "file.dcm";\nDicomFile theFile = new DicomFile(filename);\ntheFile.Load(DicomReadOptions.Default);\nforeach (DicomAttribute attribute in theFile.DataSet)\n{\n    Console.WriteLine("Tag: {0}, Value: {1}", attribute.Tag.Name, attribute.ToString());\n}	0
24252136	24252031	DateTime trying to set AM/PM for the Date	DateTime startDate = DateTime.Today;\nDateTime endDate = startDate.AddDays(1).AddSeconds(-1);	0
19263240	19262692	synchronising tabpages and their controls	int tabCount = 0;\n        foreach (TabPage tp in customTabControl1.TabPages)\n        {\n            tp.Tag = tabCount;\n            foreach (Control ctrl in tp.Controls)\n            {\n                if (ctl is YourUserControlTypeHere)\n                {\n                    YourUserControlTypeHere uc = (YourUserControlTypeHere)ctl;\n                    uc.BrowserCount = TabCount; // Error Unknown member BrowserCount\n                }\n            }\n        }	0
9839482	9839433	Set Textbox value to last month	DateTime value = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1).AddDays(-1);	0
3552742	3552610	Get containing row from a CheckBox inside of a DataGrid	FrameworkElement fe = sender as FrameworkElement;\n\nwhile ((fe.GetType() != typeof(DataGrid)) &&\n       (fe != null))\n{\n     fe = VisualTreeHelper.GetParent(fe) as FrameworkElement;\n}	0
27560173	27560037	ArgumentOutOfRangeExecption by a Insert	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    lista.Add(new Lista() { Hexnumber_op_Code = "1D", Background_OP_Code = "hallo", OP_Code = "red" });\n    lista.Add(new Lista() { Hexnumber_op_Code = "1D", Background_OP_Code = "hallo", OP_Code = "red" });\n}	0
20784946	20784855	String as a variable (Dot-notation instead bracket-notation)?	public string SQL_CONNECTION_STRING\nget{return get("SQL_CONNECTION_STRING"); }	0
29206751	29206650	How to pass n no.of different generic parameters to a method	public RecordConfiguration<TStage, TKey> EnsureUnique>(params Expression<Func<TStage, object>>[] propertyAccessors)\n{\n    // ...\n    properyAccessors.Select((val,index)=>new{ val,index})\n                    .ForEach(i =>columnSet.AddAt(i.index, i.val));\n    // ...\n}	0
12176497	12176389	C# lambda get distinct list of value conditionally	var result = users.GroupBy(u => u.UserId)\n                  .Where(g => g.Select(u => u.City).Distinct().Count() > 1)\n                  .Select(g => g.Key)\n                  .ToList();	0
5357393	5357387	Displays currency value in US culture format	double cost=5123456.55;\nConsole.WriteLine(cost.ToString("C", new System.Globalization.CultureInfo("en-US")));\n// The example displays the output: $5,123,456.55	0
18124066	18123244	getting text of particular control on rowcommand event	Dim row As GridViewRow = DirectCast(DirectCast(e.CommandSource, Control).NamingContainer, GridViewRow)\n\nCType(row.FindControl("lbActiveCheck"), LinkButton).Text = "Make As Inactive"	0
11629408	11452645	How to get path of current target file using NLog in runtime?	var fileTarget = (FileTarget) LogManager.Configuration.FindTargetByName("file");\n// Need to set timestamp here if filename uses date. \n// For example - filename="${basedir}/logs/${shortdate}/trace.log"\nvar logEventInfo = new LogEventInfo {TimeStamp = DateTime.Now}; \nstring fileName = fileTarget.FileName.Render(logEventInfo);\nif (!File.Exists(fileName))\n    throw new Exception("Log file does not exist.");	0
11607112	11607103	Check if there is phone number in string C#	[0-9]{7,}\n\nbool includesPhone = Regex.IsMatch("phone number 123456789", "[0-9]{7,}");	0
14848477	14628834	Compare listview items in two adjacent listviews, and do stuff with identical items... Taking too loooong	Private Function _find_item_in_rev(itemCode As String) As xStockitem\n    Dim myTempItem As New xStockitem\n    Debug.Print(currentRevItems.Count.ToString)\n\n    For Each thisItem As xStockitem In currentRevItems\n\n        If thisItem.stockCode = itemCode Then 'found item\n            myTempItem.stockCode = itemCode\n            myTempItem.price = thisItem.price\n            myTempItem.quantity = thisItem.quantity\n            currentRevItems.Remove(thisItem)\n            Return myTempItem\n        End If\n\n    Next\n    Return Nothing 'nothing found\nEnd Function	0
3903364	3903304	how to load html code into c# string?	string body = @"<html><body>\n<a href=""foo.bar"" class=""blap"">blip</a>\n...\n</body></html>";	0
24180514	24180470	Call a non-static class with a console application	public string NonStaticMethod()\n{\n    var instance = new MyNewClass();\n    return instance.MyStringMethod(); //Can call non static method\n}	0
30270050	30269752	Removing Controls from Form (Doesn't hit every Control I want to remove)	List<Control> controlsToBeRemoved = new List<Control>();\n    foreach (Control item in this.Controls.OfType<PictureBox>())\n    {\n        controlsToBeRemoved.Add(item);\n    }\n\n    foreach (Control item in controlsToBeRemoved)\n    {\n        this.Controls.Remove(item);\n    }	0
4409814	4409439	My InnerXML equals my OuterXML after selecting only the Childnodes with XPathNodeIterator	while (iterator.MoveNext())\n{\n    //Do Stuff\n}	0
33217757	33217618	Encryption and Decryption of files results in a blank file when decrypting	byte[] bytesToBeEncrypted = File.ReadAllBytes(files[i]);\nbyte[] passwordBytes = Encoding.UTF8.GetBytes(passWord);\n\n// Hash the password with SHA256\npasswordBytes = SHA256.Create().ComputeHash(passwordBytes);\nbyte[] bytesCyrpt = new byte[0];\nif (Mode == "Encrypt")\n{\n    bytesCyrpt = AES_Encrypt(bytesToBeEncrypted, passwordBytes);\n    File.WriteAllBytes(encryptedFileName(files[i]), bytesCyrpt);\n    File.Delete(files[i]);\n}\nelse\n{\n    bytesCyrpt = AES_Decrypt(bytesToBeEncrypted, passwordBytes);\n    File.WriteAllBytes(decryptFileName(files[i]), bytesCyrpt);\n}	0
15801502	15801344	How do I Multithread to readline in c# without pausing or interrupting the program?	using System;\nusing System.Threading;\n\nnamespace Input\n{\n    class MainClass\n    {\n        public static void Main (string[] args)\n        {\n            // This is to stop the worker thread\n            var workerShouldStop = false;\n\n            var worker = new Thread(() => \n            {\n                // do work\n                while (!workerShouldStop) {\n                    Thread.Sleep(1000);\n                    Console.WriteLine("doing things ...");\n                };\n            });\n\n            worker.Start();\n\n            string input;\n            do \n            {\n                Console.Write ("Your input (enter to quit):");\n                input = Console.ReadLine();\n                Console.WriteLine("input is:" + input);\n            } while(!String.IsNullOrWhiteSpace(input));\n\n            // Stop the worker thread\n            workerShouldStop = true;\n        }\n    }\n}	0
7685110	7685024	How to select all parent elements of a certain element?	public static IEnumerable<XElement> Parents(this XObject obj)\n{\n    XElement e = obj.Parent;\n    while (e != null)\n    {\n        yield return e;\n        e = e.Parent;\n    }\n}	0
3616156	3616133	Convert String to Datetime C#	var parsed = DateTime.ParseExact("20100825161500","yyyyMMddHHmmss", null);	0
32321034	32320973	How to get the header values in a GET request?	resp.Headers	0
3620161	3620072	Fractions in a NumericUpDown/DomainUpDown	nupdwn.Minimum = -10;\nnupdwn.Maximum = 10;\nnupdwn.Increment = 0.25;\nnupdwn.DecimalPlaces = 2;	0
9278311	9277709	Linq select 10 children for each parent item	class Program\n    {\n        static void Main(string[] args)\n        {\n            List<A> lst = new List<A>();\n\n            for (int j = 1; j < 4; j++)\n            {\n                var tmp = new A() { Value = j * 1000 };\n                for (int i = 0; i < 150; i++)\n                {\n                    tmp.SubItems.Add(new B { Value = i + 1, Parent = tmp });\n                }\n                lst.Add(tmp);\n            }\n\n            List<B> result = lst.SelectMany(x => x.SubItems.Take(10)).ToList();\n        }\n    }\n\n    public class A\n    {\n        public A()\n        {\n            SubItems = new List<B>();\n        }\n\n        public int Value { get; set; }\n        public List<B> SubItems { get; set; }\n    }\n\n\n    public class B\n    {\n        public int Value { get; set; }\n        public A Parent { get; set; }\n    }	0
10275129	10240668	Set Focus on Controls in C#	if(!postback){//code here}\n  else\n  {\n    Control cont = this.Page.FindControl(Request.Form["__EVENTTARGET"]);\n    if (cont != null)\n        cont.Focus();\n  }	0
9045770	9045676	c# - How do I loop through a time range	var startTime = DateTime.Parse("2012-01-28 18:00:00");\nvar endTime = startTime.AddHours(3);\nwhile (startTime <= endTime)\n{\n  System.Console.WriteLine(startTime.ToShortTimeString());\n  startTime = startTime.AddMinutes(30);\n}	0
1383441	1383434	How can I make a method private in an interface?	public interface IValidationCRUD\n{\n    ICRUDValidation IsValid(object obj);\n}\n\npublic abstract class ValidationCRUDBase: IValidationCRUD {\n    public abstract ICRUDValidation IsValid(object obj);\n    protected abstract void AddError(ICRUDError error);\n}	0
3203081	3180691	Broken encoding after postback	public void ReloadPage()\n{\n    UrlBuilder url = new UrlBuilder(Context, Request.Path);\n    foreach (string queryParam in Request.QueryString.AllKeys)\n    {\n        string queryParamValue = Request.QueryString[queryParam];\n        url.AddQueryItem(queryParam, queryParamValue);\n    }\n    Response.Redirect( url.ToString(), true);\n}	0
16099503	16099452	Ranking items in a list with LINQ	public class NumberRank\n{\n   public int Number {get; set;}\n   public int Rank {get; set;}\n\n   public NumberRank(int number, int rank)\n   {\n      Number = number;\n      Rank = rank;\n   }\n}\n\nclass Test\n{\n   static void Main()\n   {\n      List<int> numbers = new List<int>();\n\n      numbers.Add(650);\n      numbers.Add(150);\n      numbers.Add(500);\n      numbers.Add(200);\n\n      List<NumberRank> numberRanks = numbers.OrderByDescending(n => n).Select((n, i) => new NumberRank(n, i + 1)).ToList();\n\n      // check it worked\n      foreach(NumberRank nr in numberRanks) Console.WriteLine("{0} : {1}", nr.Rank, nr.Number);\n      Console.ReadKey();  \n   }\n}	0
1553249	1553235	To show a new Form on click of a button in C#	private void Button1_Click(Object sender, EventArgs e ) \n{\n   var myForm = new Form1();\n   myForm.Show();\n}	0
24217605	24217579	Accessing Concrete Implementation of Interface, Dependency Injection	public interface IHomeUpContext\n{\n    DbSet<channel> channel { get; set; }\n    int SaveChanges();\n}	0
6777093	6774233	C# : Split String and put it in the first column of a DataGridView	string csv = "Name,Surname,Telephone,Address";\nstring[] split = csv.Split(',');\n\nDataGridViewTextBoxColumn subject = new DataGridViewTextBoxColumn();\nsubject.HeaderText = "Subject Type";\nsubject.Name = "Subject";\n\ndataGridView1.Columns.Add(subject);\n\nforeach (string item in split)\n{\n    dataGridView1.Rows.Add(item);\n}	0
10715475	10714790	How can i lock by cache key?	public T GetCache<T>(string key, Func<T> valueFactory...) \n{\n    // note here that I use the key as the name of the mutex\n    // also here you need to check that the key have no invalid charater\n    //   to used as mutex name.\n    var mut = new Mutex(true, key);\n\n    try\n    {   \n        // Wait until it is safe to enter.\n        mut.WaitOne();\n\n        // here you create your cache\n    }\n    finally\n    {\n        // Release the Mutex.\n        mut.ReleaseMutex();\n    }   \n}	0
19875846	19875800	Strange Interlocked behavior in wp7	Interlocked.Add(ref long, long)	0
9823572	9823397	Insert Data into MySQL	com.ExecuteNonQuery();	0
12527727	12527434	Path to a document	XmlDocument doc = new XmlDocument();\ndoc.Load(Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + @"\test.xml");	0
27454312	27454275	In C#, how can i get a label to display multiple results without using additional labels?	lblOUT.Text += Convert.ToString(num2) + Environment.NewLine;	0
22359196	22356846	Enable UI virtualization on a TreeView in C#, programmatically	myTreeView.SetValue(VirtualizingPanel.IsVirtualizingProperty, true);\nmyTreeView.SetValue(VirtualizingPanel.VirtualizationModeProperty, VirtualizationMode.Recycling);	0
5240313	5239605	Inject js from IhttpModule	public void Init(HttpApplication context)\n{\n    context.PostMapRequestHandler += OnPostMapRequestHandler;\n}\n\nvoid OnPostMapRequestHandler(object sender, EventArgs e)\n{\n    HttpContext context = ((HttpApplication)sender).Context;\n    Page page = HttpContext.Current.CurrentHandler as Page;\n    if (page != null)\n    {\n        page.PreRenderComplete += OnPreRenderComplete;\n    }\n}\n\nvoid OnPreRenderComplete(object sender, EventArgs e)\n{\n    Page page = (Page) sender;\n    // script injection here\n}	0
14200592	14200204	How to get two (0~15) numbers as properties with one byte as backing field?	private byte _myByte;\npublic byte LowerHalf\n{\n    get\n    {\n        return (byte)(_myByte & 15);\n    }\n    set\n    {\n        _myByte = (byte)(value | UpperHalf * 16);\n    }\n}\npublic byte UpperHalf\n{\n    get\n    {\n        return (byte)(_myByte / 16);\n    }\n    set\n    {\n        _myByte = (byte)(LowerHalf | value * 16);\n    }\n}	0
2074853	2074779	Identifying derived types from a list of base class objects	animals.Friends = new List<Animal> { new Kangaroo(), new Bird() };\nforeach ( var kangaroo in animals.Friends.OfType<Kangaroo>()) {\n  kangaroo.Hop();\n}	0
1438792	1438767	Creating a loop that will edit 60 TextBox names?	foreach(Control c in this.Controls) {\n    if(c is TextBox)\n        Console.WriteLine(c.Text);   \n}	0
1439536	1439516	Enumerating Outlook Mailbox using Visual Studio	foreach ( MailItem oItem in theMailFolder.Items.OfType<MailItem>()) {\n  ..\n}	0
22378596	22378138	AutoMapper null source value and custom type converter, fails to map?	public TDestination Map<TDestination>(object source, Action<IMappingOperationOptions> opts)\n    {\n        var mappedObject = default(TDestination);\n        if (source != null)\n        {\n            var sourceType = source.GetType();\n            var destinationType = typeof(TDestination);\n\n            mappedObject = (TDestination)Map(source, sourceType, destinationType, opts);\n        }\n        return mappedObject;\n    }	0
11511512	11511118	How do you attach two forms together in C#?	Form.Show(ownerForm)	0
5944449	5944397	Index out of range when trying to retrieve userPrincipalName from AD	DirectorySearcher search = new DirectorySearcher("LDAP://DCHS");\nsearch.Filter = String.Format("(SAMAccountName={0})", UserName);\nSearchResult result = search.FindOne();    \nDirectoryEntry entry = result.GetDirectoryEntry();\n_UPN = entry.Properties["userPrincipalName"].Value.ToString();	0
1178908	1132143	Best practices to generate schema for production with NHibernate	new SchemaExport(config).Execute(ddlScript => {\n    using (var writer = new StreamWriter(fileName, true))\n    {\n        writer.Write(ddlScript);\n        writer.Flush();\n    }\n}, false, false);	0
5310324	5309983	How to call this Delphi function from C#?	[DllImport(@"test.dll")]\nprivate static extern void methodToCall(\n    [MarshalAs(UnmanagedType.BStr)]\n    string aFirstParameter,\n    [MarshalAs(UnmanagedType.BStr)]\n    ref string aSecondParameter\n);	0
2828589	2828042	Iserializable to serialize readonly methods to be sent through webservice	[Obsolete("For serialization only", true)]\n public Foo() {}	0
3637849	3637005	Maintaining positional integer value for numerous entries whose positions may change	++count % 23 == 0	0
5759586	5748863	How to declare DateTime property with proper DateTimeKind?	public Date deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) throws JsonParseException\n    {\n        String s = json.getAsString().replace("/Date(", "").replace(")/", "");\n\n        //if there us no data passed in - that means NULL\n        if (s.equals("")) return null;\n\n        //If we got timezone info handle separately:\n        long offset = 0;\n        if (s.length() > 5 && (s.indexOf("-") == s.length()-5 || s.indexOf("+") == s.length()-5))\n        {\n            //get offset minutes\n            offset = Long.valueOf(s.substring(s.length()-4, s.length()-2))*60 + Long.valueOf(s.substring(s.length()-2, s.length()));\n            //Apply direction\n            if (s.indexOf("-") == s.length()-5) offset = -offset;\n\n            //Cutoff offset\n            s = s.substring(0, s.length()-5);\n        }\n\n        return new Date(Long.valueOf(s) + offset * 60 * 1000);\n\n    }	0
1805545	1805462	How to draw a rectangle in Compact Edtion?	public class ColoredButton : Control {\n    protected override void OnPaint(PaintEventArgs e) {\n        Graphics graphics = e.Graphics;\n        Pen pen = new Pen(Color.Black, 1f);\n        SolidBrush brush = new SolidBrush(Color.Red);\n\n        graphics.FillRectangle(brush, 0, 0, Width, Height);\n        graphics.DrawRectangle(pen, 0, 0, Width-1, Height-1);\n    }\n}	0
8578503	8578445	Newtonsoft.Json - ignore DataContractAttribute	[DataContract]\nclass Foo \n{\n    [DataMember]\n    public string Name { get; set; }\n}	0
9544638	9544223	Property isn't serialized	public string[] MyProperty\n? ? ? ? {\n? ? ? ? ? ? get\n? ? ? ? ? ? {\n? ? ? ? ? ? ? ? List<string> list = new List<string>();\n? ? ? ? ? ? ? ? foreach (MyObject obj in ListMyObjects)\n? ? ? ? ? ? ? ? ? ? list.Add(obj.Name);\n? ? ? ? ? ? ? ? return list.ToArray();\n? ? ? ? ? ? }\n? ? ? ? ? ? set\n? ? ? ? ? ? {\n? ? ? ? ? ? ? ? foreach (string name in value)\n? ? ? ? ? ? ? ? ? ? ListMyObjects.Add(new MyObject(name));\n? ? ? ? ? ? }\n? ? ? ? }	0
12007589	12007541	Wait to get info from a popup form	Form3 getup = new Form3();\ngetup.ShowDialog();\nexample = getup.example;	0
5611372	5611363	C# executing code from one button in another	private void button1click(object sender, EventArgs e)\n{\n       Foo();\n}\n\n\nvoid EnterPressed(object sender, KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.Enter)\n    {\n        Foo();\n    }\n}\n\nvoid Foo()\n{\n    //Do Something\n}	0
2596355	2596344	default value for a static property	static MyClass()\n{\n    Initialized = false;\n}	0
1646429	1646402	Multiple DataContext/EntitiesObject	private UsersRepository _usersRepository;\nprivate  UsersRepository UsersRepository\n{\n    get\n    {\n        if(_usersRepository == null)\n        {\n            _usersRepository = new UsersRepository();\n        }\n        return _usersRepository;\n    }\n}	0
1710942	1710193	Converting an XML-document to a dictionary	string data = "<data><test>foo</test><test>foobbbbb</test><bar>123</bar><username>foobar</username></data>";\n\nXDocument doc = XDocument.Parse(data);\nDictionary<string, string> dataDictionary = new Dictionary<string, string>();\n\nforeach (XElement element in doc.Descendants().Where(p => p.HasElements == false)) {\n    int keyInt = 0;\n    string keyName = element.Name.LocalName;\n\n    while (dataDictionary.ContainsKey(keyName)) {\n        keyName = element.Name.LocalName + "_" + keyInt++;\n    }\n\n    dataDictionary.Add(keyName, element.Value);\n}	0
10852369	10852305	How can I get the IP address from the user client in C#?	var userAddress = HttpContext.Current.Request.UserHostAddress;	0
33009616	33009218	RestSharp - deserialize json response with invalid key name (contains a period )	[JsonProperty("cost_center.code")]\npublic string CostCenter{ get; set; }	0
10074802	10074609	How to have the sidebar stretch automatically	div#ContentWrapper { display: table; }\ndiv#LeftSidebar { display: table-cell; }\ndiv#MainContent { display: table-cell; }	0
24601098	24601067	How do I test if a replacement string needs to be a regular expression?	Regex.Escape(pattern) == pattern	0
662994	662880	ASP.NET Server Side Viewstate	public string PersistanceKey\n{\n    get { \n        if(ViewState["PersistanceKey"] == null)\n           ViewState["PersistanceKey"] = "Object" + Guid.NewGuid().ToString();\n\n        return (string)ViewState["PersistanceKey"];\n    }\n}\n\npublic PersistanceObject Persistance\n{\n    get {\n        if(Session[this.PersistanceKey] == null)\n            Session[this.PersistanceKey] = new PersistanceObject();\n\n        return (PersistanceObject)Session[this.PersistanceKey];\n}	0
15064813	15064779	Control hover color	private void Panel_MouseIn(object sender, EventArgs e)\n{\n  Panel pan = sender as Panel;\n  pan.BackColor = Color.Red;\n}	0
29818603	29818501	How To Split List Evenly/	int number = items.Count;\n        int number2 = number / 2;\n\n        List<TableItem> firstList = items.GetRange(0, number2);\n        List<TableItem> secondList = items.GetRange(number2, number % 2 == 0? number2 : number2 + 1);\n\n\n        listView1.Adapter = new HomeScreenAdapter(this, firstList);\n        listView2.Adapter = new HomeScreenAdapter (this, secondList);	0
30715383	30715361	Filter Foreach by boolean value in view	Model.TicketNotes.Reverse().Where(i => i.PublicFlag == false)	0
16820744	16820624	How to handle multiple services in ServiceStack?	typeof(EntryService).Assembly	0
22204857	22204389	get ListItem for each RadioButtonList in Wizard C#	foreach (WizardStep step in Wizard1.WizardSteps)\n    {\n        foreach (Control c1 in step.Controls)\n        {\n            if (c1 is Label)\n            {\n                Label1.Text += ((Label)c1).Text + "<br/><br/>";\n            }\n\n            if(c1 is RadioButtonList)\n            {\n              foreach (ListItem li in ((RadioButtonList)c1).Items)\n              { \n                Label1.Text += li.Text + "<br/><br/>";\n              }\n            }\n        }\n    }	0
21960377	21953525	How to design a game for multiple resolutions?	const double aspect = windowWidth / windowHeight;\nif (aspect > 1.0) {\n  GL.Ortho(-1 * aspect, 1 * aspect, -1, 1, -1.0, 1.0);\n} else {\n  GL.Ortho(-1, 1, -1 / aspect, 1 / aspect, -1.0, 1.0);\n}	0
6259406	6259376	How to add input check in a Linq Query to build XML only if input is valid	XDocument classes = new XDocument(\n                      new XElement("Classes", String.IsNullOrEmpty(classInput) ?\n                          null :\n                          new XElement("Class",\n                              new XElement("Name", classInput))\n                    ));	0
1620924	1620862	LINQ-To-SQL OrderBy with DateTime Not Working	(Linq-To-Sql-Expression).Distinct().OrderByDescending(x => x.TIMECARDDATE).ToList()	0
11719042	11718017	Reusing structs from C in C#	#ifdef CLIEXPORT\n#define value\n#endif\n\nCLIEXPORT struct MyCStruct\n{\n    unsigned long A;\n    unsigned long B;\n    unsigned long C;\n};	0
7713530	7713070	Unit Testing ServiceLayer with lambda and Moq	fakeCompanyRepository.Setup(\n  u => u.Find(It.IsAny<Expression<Func<Company, bool>>>()))\n  .Returns(\n     //Capture the It.IsAny parameter\n     (Expression<Func<Company, bool>> expression) => \n     //Apply it to your queryable.\n        companies.AsQueryable().Where(expression));	0
22742150	22728991	What is a best approach for multithreading on SerialPort	private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n    {\n       //the SetXXXXX functions are using the .InvokeRequired approach \n       //because the UI components are updated from another thread than \n       //the thread they were created in\n\n        SetStatusLabel("Iddle...", lbStatus);\n        SetPicVisibility(Form1.frm.ledNotReceiving, true);\n        SetPicVisibility(Form1.frm.ledReceiving, false);\n        String st = serialPort1.ReadLine();\n        if (st != null)\n        {\n            lines.Enqueue(st);\n            Task.Factory.StartNew(() => StartDataProcessing(lines)); // lines is global ConcurrentQueue object so in fact there is no need to pass it as parameter\n            SetStatusLabel("Receiving data...", lbStatus);\n            SetPicVisibility(Form1.frm.ledNotReceiving, false);\n            SetPicVisibility(Form1.frm.ledReceiving, true);\n        }\n    }	0
14112886	14112815	Windows 7 Default Network Adapter	if (nic.Supports(NetworkInterfaceComponent.IPv4)) // means IPv4 support is present	0
33761246	33760418	How to force a prompt for credentials when launching a program and UAC is disabled?	ProcessStartInfo.Verb = "runasuser"	0
9667929	9667899	Unable to follow tutorial to create dynamic search results	[System.Web.Script.Services.ScriptService]\n[System.Web.Script.Services.GenerateScriptType(typeof(searchResult))]\npublic class SearchService : WebService\n{\n  [WebMethod]\n  public searchResult[] Search(string txtSearch)\n  {\n     // ...\n  }\n}	0
4892091	4891013	Gridview FindControl finds Calendar, but not DropDownList	protected void GridViewSelections_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if ((e.Row.RowType == DataControlRowType.DataRow) && (e.Row.RowState.HasFlag(DataControlRowState.Edit) && (e.Row.DataItem != null)))\n    {\n        DropDownList ddlOptions = e.Row.FindControl("ddlOptions") as DropDownList;\n        ddlOptions.Items.Add(new ListItem("aaa", "1"));\n        ddlOptions.Items.Add(new ListItem("bbb", "2"));\n        ddlOptions.Items.Add(new ListItem("ccc", "3"));	0
1216450	509967	How can one find unknown XML namespaces in a document?	// Match every element and attribute in the document\nvar allNodes = xmlDoc.SelectNodes("//(*|@*)");\nvar found = new Dictionary<String, bool>(); // Want a Set<string> really\nforeach (XmlNode n in allNodes) {\n  found[n.NamespaceURI] = true;\n}\nvar allNamespaces = found.Keys.OrderBy(s => s);	0
22520010	22519909	JSON stringified array to mvc 4 c# array	//in the file where you use JsonConvert\nusing Newtonsoft.Json;\n\npublic class item\n{\n    public int id { get; set; }\n    public int aantal { get; set; }\n}\n\n\nitem[] myItems = JsonConvert.Deserialize<item[]>(jsonString);	0
3598295	3572627	How to call an external URL from a ASP.NET MVC solution	string messageToCallInPatient = "The doctor is ready to see you in 5 minutes. Please wait outside room " + roomName;\n string url = "http://x.x.x.x/cgi-bin/npcgi?no=" + phoneNumber + "&msg=" +\n               messageToCallInPatient;\n HttpWebRequest webReq = (HttpWebRequest)WebRequest.Create(string.Format(url));\n webReq.Method = "GET";\n HttpWebResponse webResponse = (HttpWebResponse)webReq.GetResponse();\n\n //I don't use the response for anything right now. But I might log the response answer later on.   \n Stream answer = webResponse.GetResponseStream();\n StreamReader _recivedAnswer = new StreamReader(answer);	0
9728549	9728262	GridView on rowdatabound , edit,delete,select options dissappeared	string search= textbox1.text;\n\nprotected void grd_RowDataBound(Object sender, GridViewRowEventArgs e)\n{           \n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        foreach(TableCell tc in e.Row.Cells)\n        {\n            if (tc.Controls.Count == 0){\n                tc.Text = tc.Text.Replace(search, "<span style='color:Red;'>" + search + "</span>");\n            }\n        }\n    }            \n}	0
14751352	14751186	How to encrypt password/email c#	new System.Net.NetworkCredential	0
33977062	33975828	Assigning to an array field through reflection in c#	else if (fieldType.IsArray)\n{\n    string[] values = ReadUntil(']');\n    var elementType = fieldType.GetElementType();\n    if (elementType == typeof(string))\n        thisField.SetValue(newObj, values);\n    else\n    {\n        var actualValues = Array.CreateInstance(elementType, values.Length);\n        for (int i = 0; i < values.Length; i++)\n            actualValues.SetValue(Convert.ChangeType(values[i], elementType), i);\n        thisField.SetValue(newObj, actualValues);\n    }\n}	0
586898	586821	How do i replace a linq object from a method call	class Foo {\n  ...\n  public static void Save(ref Foo obj)\n  {\n    var newObj = obj._save() //your implementation\n    obj = newObj;\n  }\n}	0
34565293	34565225	IF blocks to LOOP	PictureBox tmp = new PictureBox();\ntmp.Bounds = pbxDators.Bounds;\n\ntmp.SetBounds(tmp.Location.X, tmp.Location.Y, 1, 15);\n\nfor (var i = 3; i >= -3; i--)\n{\n    if (dt.Bounds.IntersectsWith(tmp.Bounds))\n    {\n        atskanotAudio(1);\n        bumbasStiprums = i;\n        return true;\n    }\n\n    tmp.SetBounds(tmp.Location.X, tmp.Location.Y + 10, 1, 15);\n}\n\nreturn false;	0
681173	681062	how can I access the formula in an excel sheet with c#?	formula = worksheet.Cells(1, 1).Formula	0
3777061	3777038	How to take whole Html /xhtml file in single string to write?	string html = File.ReadAllText(@"C:\myhtmlfiles\index.html");\n\nFile.WriteAllText(@"c:\someotherfile.html", html);	0
2313373	2313334	LINQ Dynamic Where - string parameter missing	using System.Linq.Dynamic	0
19389901	19378123	Webforms C# client side validation CustomValidator using WebAPI	[Required, StringLength(100), Display(Name = "Name")]\n public string ProductName { get; set; }	0
18765860	18765554	C# How To Sort Two Columns By Hierarchy	column[0]	0
17266670	17266411	Cant figure out why my server is not continue listening to data sent from the client	private void AcceptCallback(IAsyncResult AR)\n    {\n        try\n        {\n            sckc = sck.EndAccept(AR);\n            buffer = new byte[sckc.ReceiveBufferSize];\n            sckc.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);\n        }\n        catch\n        {\n\n        }\n    }\n\n    private void ReceiveCallback(IAsyncResult AR)\n    {\n        try\n        {\n            string text = Encoding.ASCII.GetString(buffer);\n            MessageBox.Show(text);\n\n            sckc.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), null);\n        }\n        catch\n        {\n\n        }\n    }	0
27638458	27638303	How do I pass variable number of arguments to GET in WebAPI	public ActionResult Method()\n{\n    foreach(string key in Request.QueryString) \n    {\n        var value = Request.QueryString[key];\n    }\n}	0
17010964	17010943	how can i get the directory of where i run my application exe file from?	Assembly.GetExecutingAssembly().Location //is what you need here	0
17915347	17915275	Converting code segment from C++ to C#	if ((latch_state & 0x1) != 0)	0
16371453	16371073	how to spilit list into sublists in C# without using LINQ	public static List<List<string>> ListToSublists(List<string> lsSource)\n        {\n            List<List<string>> lsTarget = new List<List<string>>();\n\n            List<string> ls = null;\n            for (int i = 0; i < lsSource.Count; ++i)\n            {\n                if (i % 100 == 0)\n                {\n                    if(ls != null)\n                        lsTarget.Add(ls);\n                    ls = new List<string>();\n                }\n                ls.Add(lsSource[i]);\n            }\n\n            if(ls != null)\n                lsTarget.Add(ls);\n            return lsTarget;\n        }\n\n\n\n\n    public static void main()\n    {\n        var yourlist = new List<string>();\n        yourlist.AddRange( /* Whatever */ ); \n        List<List<string>> ls = ListToSublists(yourlist );\n\n        foreach (List<string> result in ls)\n        {\n\n            if (result.Count > 0)\n            {\n                handler.send(result.ToArray(), smscontext);\n            }\n\n        }\n    }	0
1739791	1739771	Please explain this regex	(?: = match but don't capture\n\n\s*? = any number of whitespace (not greedy)\n\n</img> = close image tag\n\n)? = zero or one times	0
4128901	4128886	c# loop through combobox where datasource is a datatable with text	foreach(object item in myComboBox.Items)\n{\n   DataRowView row = item as DataRowView;\n\n   if(row != null)\n   {\n        string displayValue = row["myColumnName"].ToString();\n\n        // do something\n   }\n   else\n       // error: item was not of type DataRowView\n}	0
3182047	3182000	How to get runtime-argument info from extression tree parameter array	var typeargs = CreateArgs(method.GetParameters());\nreturn Expression.Lambda(\n    type,\n    Expression.Call(_delegate.Method, Expression.NewArrayInit(typeof(object),\n        typeargs.Select(arg => Expression.Convert(arg, typeof(object)))\n        )),\n    typeargs\n).Compile();	0
7352378	7352358	Reading specific part of a File Content	Using reader = file.OpenText()\n    Dim line As String\n    While True\n        line = reader.ReadLine()\n        If ReferenceEquals(Line, Nothing) Then Exit While\n\n        'Parse the line and figure out what to do with it\n    End While\nEnd Using	0
8080564	8080158	Need help finding the second Wednesday of a year	var year = 2011;\nvar firstDayOfMonth = new DateTime(year, 1, 1);\nvar daysUntilNextWednesday = DayOfWeek.Wednesday - firstDayOfMonth.DayOfWeek;\nif (daysUntilNextWednesday < 0)\n  daysUntilNextWednesday += 7;\nvar firstWednesdayOfMonth = firstDayOfMonth.AddDays(daysUntilNextWednesday);\nvar secondWednesdayOfMonth = firstWednesdayOfMonth.AddDays(7);	0
20859391	20858896	MongoDB Select with QueryBuilder	// But everything in the Query\nIMongoQuery mongoQuery = query.Or(ids);\n\n// Add Queryattributes if there\nif (queryattributes.Count > 0)\n{\n    mongoQuery = query.And(queryattributes);\n}\n\nvar result = collection.FindAs<Datapoint>(mongoQuery);	0
22496143	21395078	Release Control of Outlook	var thread = new Thread(() => Method(Parameters));\nthread.Start();	0
12621657	12621640	Rounding a variable to two decimal places C#	Math.Round(pay,2);	0
31252006	31251878	Using a while loop in a switch statment	bool valid;\n    do\n    {\n        valid = true;\n        userChoice1 = Console.ReadLine();\n        switch (userChoice1)\n        {\n            case "1":\n                msg = "\n\nYou have chosen the House Salad with Ranch Dressing. \nPress enter to continue.";\n                saladChoice = "House Salad with Ranch Dressing";\n                break;\n            case "2":\n                msg = "\n\nYou have chosen the Caesar Salad. \nPress enter to continue. ";\n                saladChoice = "Caesar Salad";\n                break;\n            default:\n                msg = "\n\nYou have chosen an invalid option. You should have selected  \n1 for the House Salad \nor \n2 for the Caesar Salad. ";\n                valid = false;\n                Console.Beep();\n                break;\n        }\n    } while (!valid);	0
17097509	17097009	RedirectToAction in MVC3 returns "No route in the route table matches the supplied values"	public static void RegisterRoutes(RouteCollection routes)\n{\n    routes.IgnoreRoute("{resource}.axd/{*pathInfo}");\n\n    routes.MapRoute(\n        "Default", // Route name\n        "{controller}/{action}/{id}/{id1}/", // URL with parameters\n        new { controller = "Home", \n              action     = "Index", \n              id         =  UrlParameter.Optional, \n              id1        =  UrlParameter.Optional \n            } // Parameter defaults\n    );\n\n    routes.MapRoute(\n        "Default", // Route name\n        "{controller}/{action}", // URL with parameters\n        new { controller = "Home", action = "Index" } // Parameter defaults\n    );\n}	0
26612880	26612846	VB to C# conversion of Byte	byte[] foo = {155, 253, 147, 202, 22, 59, 228, 6, 61, 16, 158, 60, 47, 138, 40, 178};	0
10136030	10135995	How to set MVC default page?	routes.MapPageRoute("DefaultPage", "", "~/Index.aspx"); \nroutes.IgnoreRoute("{resource}.aspx/{*pathinfo}");	0
25497996	25424816	How to read a PDF file line by line in c#?	PdfReader reader = new PdfReader(@"D:\test pdf\Blood Journal.pdf");\n        int intPageNum = reader.NumberOfPages;\n        string[] words;\n        string line;\n\n        for (int i = 1; i <= intPageNum; i++)\n        {\n            text = PdfTextExtractor.GetTextFromPage(reader, i, new     LocationTextExtractionStrategy());\n\n            words = text.Split('\n');\nfor (int j = 0, len = words.Length; j < len; j++)\n            {\n                line = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(words[j]));	0
15067080	15067063	How to check if domain exists	public static void DoGetHostEntry(string hostname)\n{\n    IPHostEntry host;\n\n    host = Dns.GetHostEntry(hostname);\n\n    Console.WriteLine("GetHostEntry({0}) returns:", hostname);\n\n    foreach (IPAddress ip in host.AddressList)\n    {\n        Console.WriteLine("    {0}", ip);\n    }\n}	0
27707040	27706892	C# extract data from start of StringBuilder	public static class StringBuilderExtensions {\n    public static String Extract(this StringBuilder source, int length) {\n      if (Object.ReferenceEquals(null, source))\n        throw new ArgumentNullException("source");\n      else if ((length < 0) || (length > source.Length))\n        throw new ArgumentOutOfRangeException("length");\n\n      // Your actual algorithm\n      String result = source.ToString(0, length);\n\n      source.Remove(0, length);\n\n      return result;\n    }\n  }\n\n  ...\n\n  StringBuilder data = ...\n  String s = data.Extract(len); // <- Just extract	0
13303688	13303519	Update MySQL Row using ADO.NET	Please you done like that ex: \n\nSqlConnection sqlConnection1 = new SqlConnection("Your Connection String");\nSqlCommand cmd = new SqlCommand();\n\ncmd.CommandText = "insert into tablename(colname1,columnname2) values(val1,val2)";\ncmd.CommandType = CommandType.Text;\ncmd.Connection = sqlConnection1;\n\nsqlConnection1.Open();\n\ncmd.ExecuteNonQuey();\n\nsqlConnection1.Close();	0
3990998	3990919	Finding Child Objects in ViewBox/Canvas Object	GeneralTransform transform = sendingObj.TransformToVisual(Application.Current.RootVisual);\nPoint pnt = transform.Transform(e.GetPosition(sendingObj));\nvar elements = VisualTreeHelper.FindElementsInHostCoordinates(pnt,Application.Current.RootVisual);	0
1788535	1788508	Calculate date with monday as dayofweek=1	public static DateTime calcMondayDate(DateTime input) {\n    int delta = (DayOfWeek.Monday - input.DayOfWeek - 7) % 7;\n    DateTime monday = input.AddDays(delta);\n    return monday;\n}	0
4555159	4554958	Is it possible to add two nodes at a time dynamically to a treeview	TreeNode node = tvwACH.SelectedNode;\n  node.Nodes.Add(filename);\n  node.Nodes.Add("Node");	0
24897260	24896925	Super slow performance of querying a DataTable with LINQ	var rowsPerEmployee =\n    (from DataRow row in dt.Rows\n     let emp = row["Emp"].ToString().Trim()\n     group row by emp into g\n     select g)\n    .ToDictionary(\n        g => g.Key,\n        g => g.ToArray());\n\nforeach (var current in rowsPerEmployee.Keys)\n{\n    var empRows = rowsPerEmployee[current];\n    ... rest of your code here, note that empRows is not all the rows for a single employee\n    ... and not just the lastname or similar\n}	0
8330296	8330262	How to increment index on a particular value in Parallel.For?	Parallel.ForEach(Enumerable.Range(0, 5).Select(i => i*2), i =>\n{\n  Console.WriteLine(i);\n});	0
25809844	25633527	Transpose a List<T> using c#	var typed = invalidDataList\n                 .GroupBy(d => d.Type)\n                 .Select(g => new\n                     {\n                         Type = g.Key,\n                         Data = g.Select(d => d.Data).ToList()\n                     })\n                 .ToList();\n\nvar table =  new DataTable();\nforeach(var type In typed)\n{\n    table.Columns.Add(type.Type);\n}\n\nvar maxCount = typed.Max(t => t.Data.Count);\nfor(var i = 0; i < maxCount; i++)\n{\n    var row = table.NewRow();\n    foreach(var type in typed)\n    {\n        if (type.Data.Count > i)\n        {\n            row[type.Type] = type.Data[i]\n        }\n    }\n\n    table.Rows.Add(row);\n}	0
513771	513440	Parsing XML from the National Weather Service SOAP Service in C# LINQ to XML	using System.Xml.Linq;\n \\...\n\n XDocument xmlDoc = XDocument.Load("YourXml.xml");\n var maximums = from tempvalue in xmlDoc.Descendants("temperature").Elements("value")\n                           where tempvalue.Parent.Attribute("type").Value == "maximum"\n                           select (string)tempvalue;\n\nList<string> returnme = maximums.ToList<string>();\nreturn returnme;	0
12576830	12576770	Casting a string to a generic	result = (T)(object)GetStringInput();	0
33135731	33135572	Accessing data members of an inherited class	((Manager)emp1).BonusEarned = Convert.ToDecimal(txtBonus.Text);\n((Manager)emp1).Department = comboDepartment.SelectedText;\n((Manager)emp1).OfficeLocation = txtOffice.Text;	0
34543482	34543416	How to zip a folder and a file?	zip.AddFile(pathTempFiles + csvFileName, directoryPathInArchive: "Attachments");	0
10523896	10523718	Split a entity collection into n parts	var result = dbContext.VisitDates\n                      .GroupBy(x => x.VisitMeDate.Date)\n                      .Where(g => g.Count() == 3)\n                      .Select(g => g.ToList())\n                      .ToList();	0
7456740	7456712	What to do with interprocess communication between two processes?	Process appB = Process.Start("C:\\applicationb.exe");\nappB.WaitForExit();\nint exitCode = appB.ExitCode;	0
21780256	21780169	how to use a asp.net validator with two buttons, but one textbox	CausesValidation="false"	0
1381163	1381097	Regex: get the name of captured groups in C#	GroupCollection groups = regex.Match(line).Groups;\n\nforeach (string groupName in regex.GetGroupNames())\n{\n    Console.WriteLine(\n       "Group: {0}, Value: {1}",\n       groupName,\n       groups[groupName].Value);\n}	0
22845258	14176673	SSL received a record that exceeded the maximum permissible length when modifying request with fiddler	if ( (oS.hostname == sSecureEndpointHostname) && (oS.port==7777)\n    && !oS.HTTPMethodIs("CONNECT")) {	0
21166597	21166340	Create a thread that starts multiple other threads	public class GetDemData\n{\n\n    List<string> addresses = new List<string>();\n\n    public void AddDataToBeCollected(string address)\n    {\n        adresses.Add(address);\n    }\n\n    public Task CollectData()\n    {\n                var webclient = new WebClient();\n                var tasks = from address in addresses\n                            select webclient.DownloadStringTaskAsync(address);\n\n                return Task.WhenAll(tasks.Select(\n                            async (downloadTask) => \n                            {\n                                 var result = await downloadTask;\n                                 //Do somthing with result\n                            }));\n    }\n\n}\n\n\npublic async Task<ActionResult> GetData()\n{\n    var data = new GetDemData();\n    // fill data with addresses\n    await data.CollectData();\n\n    return View();\n}	0
6357976	6357899	Assign Null value to the Integer Column in the DataTable	DR["CustomerID"] = string.IsNullOrWhiteSpace(text)\n        ? DBNull.Value : (object)Convert.ToInt32(text);	0
3978794	3978722	How are IDisposable objects passed to base constructor arguments handled in C# if initialization fails?	[SuppressMessage("Microsoft.Reliability",\n                 "CA2000:DisposeObjectsBeforeLosingScope",\n                 Justification = "Your reasons go here")]\npublic YourClass(IDisposable obj) : base(obj)\n{\n}	0
12963614	12962992	Invalid length for a Base-64 char array exception	while ((encodedMsg.Length * 6) % 8 != 0) encodedMsg += "=";\n// etc...	0
11915762	11915678	C# Convert Int To Two Hex Bytes?	var input = 16;\n\nvar bytes = new byte[2];\nbytes[0] = (byte)(input >> 8);  // 0x00\nbytes[1] = (byte)input;         // 0x10\n\nvar result = (bytes[0] << 8)\n           | bytes[1];\n\n// result == 16	0
20585672	20585649	Exit C# application from second form	protected override void OnFormClosing(FormClosingEventArgs e)\n{\n\n\n   DialogResult dgResult = MessageBox.Show(this, "Are you sure you want to exit?", "", MessageBoxButtons.YesNo); \n    if(dgResult==DialogResult.No)\n            e.Cancel = true;\n\n      else\n     //here  you can use  Environment.Exit  which is not recomended because it does not generate a message loop to notify others form\n      Environment.Exit(1);  \n        //or  you can use\n         //Application.Exit();  \n}	0
15998237	15998071	Getting past Open-Closed Principle	public class Context {\n   public Point BeginPoint;\n   public Point EndPoint;\n   public List Points;\n\n   whatever else\n}\n\npublic class ShapeFactory {\n\n   List<FactoryWorker> workers;\n\n   public Shape CreateShape( string ShapeName, Context context )\n   {\n      foreach ( FactoryWorker worker in workers )\n         if ( worker.Accepts( ShapeName ) )\n             return worker.CreateShape( context );\n   }\n\n   public void AddWorker( FactoryWorker worker ) {\n      workers.Add( worker );\n   }\n }\n\n public abstract class FactortWorker {\n    public abstract bool Accepts( string ShapeName );\n    puboic Shape CreateShape( Context context );\n }\n\n public class PolyLineFactoryWorker : FactoryWorker {\n\n    public override bool Accepts( string ShapeName ) {\n       return ShapeName == "polyline";\n    }\n\n    public Shape CreateShape( Context context ) { ... }\n\n }	0
9175947	9175704	How to get focused elements of specific process in c#	Process pr	0
1298929	1298883	How to add columns & rows dynamically during runtime by code in GridView	myGridView.Columns.Add(new BoundField { DataField = "MyColumn", DataFormatString = "My Data is: {0}" });\nmyGridView.DataSource = myDataSource; // where your datasource contains your additional records\nmyGridView.DataBind();	0
27722044	27720027	Why must I implement a function for an interface in vb.net which apparently doesn't need to be implemented in C#	Partial Public Class CustomerController\n    Implements ICustomerController\n\n    Public Function GetCustomerSelectionViewData(ByVal stateFilter As String) As CustomerSelectionViewData Implements ICustomerController.GetCustomerSelectionViewData\n        Return Nothing\n    End Function\n\n    Public Sub UpdateCustomer(ByVal data As CustomerEditViewData) Implements ICustomerController.UpdateCustomer\n    End Sub\nEnd Class\n\nPartial Public Class CustomerController\n    Inherits BaseController\n    Implements ICustomerController\n\n    Public Sub EditCustomer(ByVal customerId As Integer, ByVal daddy As BaseViewModel) Implements ICustomerController.EditCustomer\n    End Sub\n\n    Public Sub CustomerSelectedForEdit(ByVal data As CustomerListItemViewData, ByVal daddy As BaseViewModel) Implements ICustomerController.CustomerSelectedForEdit\n    End Sub\nEnd Class	0
26853750	26847867	Limit characters per line in the multiline textbox in windows form application	private void txtNewNotes_KeyDown(object sender, KeyPressEventArgs e)\n        {\n            if (txtNewNotes.Text.Length == 0) return;\n\n            if (e.KeyChar == '\r')\n            {\n                e.Handled = false;\n                return;\n            }\n\n            if (e.KeyChar == '\b')\n            {\n                e.Handled = false;\n                return;\n            }\n\n            int index = txtNewNotes.GetLineFromCharIndex(txtNewNotes.SelectionStart);\n            string temp = txtNewNotes.Lines[index];\n            if (temp.Length < 45) // character limit\n            {\n                e.Handled = false;\n            }\n            else\n            {\n                e.Handled = true;\n            }\n        }	0
4864849	4864492	need clarification on Datatable	public class FooView\n{\n   public FooView(Row row)\n   {\n      this.Row = row;\n   }\n\n   private Row Row { get; set; }\n\n   public string Server { get { (string)return this.Row["Server"]; } }\n   public string Blah{ get { (string)return this.Row["blah"]; } }\n   public string Link1{ get { string.Format("http://foo.bar/id={0}", this.Server); } }\n}	0
19517050	19517004	Showing Plain Text of a Password TextBox in C#	private void chkpwd_CheckedChanged(object sender, EventArgs e)\n    {\n        if (chkpwd.Checked)\n            txtpwd.PasswordChar = '\0';\n        else\n            txtpwd.PasswordChar = '*';\n    }	0
13851357	13851173	How to read Swedish characters properly from a txt file	System.IO.TextReader tr = new System.IO.StreamReader(@"c:\testfile.txt", System.Text.Encoding.GetEncoding(1252), true);\n        tr.ReadLine(); //returns a string but Swedish characters are not appearing correctly	0
3502970	3502852	How to convert datatable into generic type	return table.AsEnumerable()\n    .Select(r => new KeyValuePair<long, string>(r.Field<long>("longFieldName"), r.Field<string>("stringFieldName")))\n    .ToArray();	0
25500365	25499738	I need to eliminate special characters using regex	(?:[^\w ]+|_+)	0
9751599	9751512	Remove null bytes from the beginning of a stream	int index = 0;\nint currByte = 0;\n\nwhile ((currByte = bbrs.ReadByte()) == 0x00)\n{\n    index++;\n}\n\n// now currByte and everything to the end of the stream are the bytes you want.	0
2574978	2574958	how to copy attribute XML node to specified structure or array	alstout.AddRange(docHarf.SelectNodes("//adatesmi")\n    .Select(n => new PossibilityJavamed {\n        derv  = n.Attributes["derv"].Value,\n        dervt = n.Attributes["dervt"].Value,\n        num   = n.Attributes["num"].Value,\n        gend  = n.Attributes["gend"].Value\n    }));	0
1369670	1358720	NHibernate Get Collection of object A based on aggregates roots id	public IList<B> GetAsBs(A aClass)\n            {\n            string hql = @"\n                SELECT B\n                FROM    A a\n                JOIN     a.ClassBs b\n                WHERE  A.ID = :ID\n            ";\n            IQuery query = Session.CreateQuery(hql);\n            query.SetParameter("ID", aClass.ID);\n\n            return query.List<B>();\n}	0
15454077	15453866	Convert Nested For Loops into a LINQ Expression	private static ISet<int> CalcSumsOfTwoNums2(IEnumerable<int> nums)\n{\n    // get List<int> from nums to get info about collection length\n    var source = nums.ToList();\n\n    // proper iteration\n    var data = source.Take(source.Count - 1)\n                     .SelectMany((e, ix) => source.Skip(ix)\n                                                  .Take(source.Count - 1 - ix)\n                                                  .Select(i => new { e, i }))\n                     .Select(x => x.e + x.i)\n                     .Where(x => x < MAX);\n\n    // return HashSet instead of IEnumerable<int>\n    return new HashSet<int>(data);\n}	0
11364651	11364481	DateTime Round Up and Down	case RoundingDirection.Up:\n    t = dt.AddMinutes((60 - dt.Minute) % 10);\ncase RoundingDirection.Down:\n    t = dt.AddMinutes(-dt.Minute % 10);	0
4058700	4058667	How to count how many listeners are hooked to an event?	MessageReceived.GetInvocationList().Length	0
1934568	1934529	How to loop over the rows of a WPF toolkit Datagrid	public IEnumerable<Microsoft.Windows.Controls.DataGridRow> GetDataGridRows(Microsoft.Windows.Controls.DataGrid grid)\n    {\n        var itemsSource = grid.ItemsSource as IEnumerable;\n        if (null == itemsSource) yield return null;\n        foreach (var item in itemsSource)\n        {\n            var row = grid.ItemContainerGenerator.ContainerFromItem(item) as Microsoft.Windows.Controls.DataGridRow;\n            if (null != row) yield return row;\n        }\n    }	0
18629584	18629101	Windows Service - read partial configuration file while service is running	ConfigurationManager.RefreshSection("appSettings")	0
2836353	2835747	LayoutMdi fails in form's OnLoad event	protected override void OnShown(EventArgs e) {\n        var f2 = new Form2();\n        f2.MdiParent = this;\n        f2.Show();\n        f2 = new Form2();\n        f2.MdiParent = this;\n        f2.Show();\n        this.LayoutMdi(MdiLayout.TileVertical);\n    }	0
19605861	19598138	Generating C# code from XML: how to output '<' and '>'?	class Program\n{\n    static void Main(string[] args)\n    {\n        if (args.Length != 3)\n        {\n            Console.WriteLine("You have not entered the correct parameters");\n            return;\n        }\n        string xmlfile = args[0];\n        string xslfile = args[1];\n        string outfile = args[2];\n        try\n        {\n            XPathDocument doc = new XPathDocument(xmlfile);\n            XslCompiledTransform transform = new XslCompiledTransform();\n            transform.Load(xslfile);\n            XmlWriter writer = XmlWriter.Create(outfile, transform.OutputSettings);\n            transform.Transform(doc, writer);\n            writer.Close();\n        }\n        catch (Exception e)\n        {\n            Console.WriteLine(e.StackTrace);\n        }\n    }\n}	0
11403151	11402949	Using htmlagility pack to replace src values	static void Main(string[] args)\n{\n    var htmlDoc = new HtmlDocument();\n    htmlDoc.Load(@"E:\Libs\HtmlAgilityPack.1.4.0\htmldoc.html");\n\n    foreach(HtmlNode node in htmlDoc.DocumentNode\n                                   .SelectNodes("//img[@src and (@width or @height)]"))\n    {\n        var src = node.Attributes["src"].Value.Split('?');\n\n        var width = node.Attributes["width"].Value.Replace("px", "");\n\n        var height = node.Attributes["height"].Value.Replace("px", "");\n\n        node.SetAttributeValue("src",\n                                src[0] +\n                                string.Format("?width={0}&height{1}", width, height));\n    }\n}	0
31358998	31358948	Remove value from bitwise or-combined integer?	private int RemoveInteger(int a, int b)\n{\n    return a & ~b;\n}	0
24178921	24178773	How to create new string each time new item is created?	Random random = new Random();\nint randomNumber  = random.Next(1, listboxname.Items.Count);\nlistboxname.Select();\nlistboxname.SelectedItem = listboxname.Items[randomNumber];\nMessageBox.Show(listboxName.SelectedItem.ToString());	0
1589196	1589167	Creating a C# object in javascript	var preparedParameters = {\n    ClassName: "Some name",\n    ClassValue: 10\n};	0
13247919	13247681	How to access Embedded Resource from code behind in MvcContrib?	var assembly = Assembly.GetExecutingAssembly();\nvar imageStream = _assembly.GetManifestResourceStream(\n        "[AssemblyNamespace].Controls.images.expander_opened_hover.png");\nvar bitmap = new Bitmap(imageStream)	0
3150600	3150485	listview checkbox checked row item	ListView.CheckedListViewItemCollection checkedItems = \n            ListView1.CheckedItems;\n\n        foreach ( ListViewItem item in checkedItems )\n        {\n            value = item.SubItems[1].Text;\n        }	0
19107212	19107169	How do I append List<string> in the following recursive function	Directory.GetFiles	0
16714352	16714163	How to avoid copy/paste many event handlers	WaitForDataLoading((s,e) => FirstMenuItem_Click(null, null));	0
25022846	24959933	Reading XML ElementExtensions in C# Win8.1 App	var allImages = item.GetXmlDocument(feed.SourceFormat).GetElementsByTagName("content");\nforeach (var s in allImages)\n{\nDebug.WriteLine(s.Attributes.GetNamedItem("url").InnerText;)\n}	0
7588911	7588797	MVC2 scaffolding - can't see any data	public class UsersController : Controller \n{ \n\n    // static List<Users> users = GetSeededData(); - \n    // don't store a list locally, it isn't necessary if you have a database\n    // consider holding the context instead perhaps?\n    protected MyContext context = new MyContext();\n\n    // \n    // GET: /Users/ \n\n    public ActionResult Index() \n    { \n        return View(context.users.ToList()); \n    } \n\n    // \n    // GET: /Users/Details/5 \n\n    public ActionResult Details(int userId) \n    { \n        return View(context.Users.SingleOrDefault(x => x.UserId.Equals(userId)); \n    } \n\n}	0
27720196	27719807	syntax error insert into database	command.CommandText = String.Format(@"INSERT INTO [membre] (Player, [Password], Gun, Claass) VALUES('" + player.Text + "', '" + password.Text + "', '" + gun.Text + "', '" + kind.Text + "')");	0
27704299	27703533	How can I remove 1 element in xml based on matched attribute and value?	List<XmlNode> toDelete = new List<XmlNode>();\n\nforeach (XmlNode value in node.SelectNodes("//Value[@uomid]"))\n{\n    if (value.Attributes["uomid"].Value == multipleUOM.ToString() &&\n        value.InnerText == valueToMatch.ToString())\n    {\n        toDelete.Add(value);\n    }\n}\nforeach (XmlNode value in toDelete)\n{\n    value.ParentNode.RemoveChild(value);\n}	0
17946384	17946072	Simple Regex Befuddlement	var guid = Guid.NewGuid().ToString();\nvar r = Regex.Replace(strA, @"'.*'", m =>\n{\n    return m.Value.Replace(":", guid);\n})\n.Split(':')\n.Select(s => s.Replace(guid, ":"))\n.ToList();	0
14501922	14501828	How group elements in LINQ to get result like Facebook messages	var myDocs = MyDatabaseContext.Documents\n                              .Where(e => e.FromCompanyId == Id ||\n                                          e.ToCompanyId == Id)\n                              .Select(x => new { OtherCompanyId\n                                                   = (x.FromCompanyId == Id) ? \n                                                      x.ToCompanyId : \n                                                      x.FromCompanyId,\n                                                 Document = x });\n\nvar docGroups = from m in myDocs\n                group m by m.OtherCompanyId into g\n                select new { ToCompanyIdKey = g.Key,\n                             BetweenDocs = g.Select(x => x.Document) };	0
16694052	16693479	Datagrid Rows Loop	foreach (GridViewItem  gvr in dgGrid.Items)\n{\n\n    //BLA BLA BLA...\n}	0
8022262	8022214	Looping over an array - getting every other item?	for (int i = 0; i < keys.Length; i += 2)\n            {\n                string titleKey = keys[i];\n                string messageKey = keys[i+1];\n                string titleVal = values.Get(titleKey);\n                string messageVal = values.Get(messageKey);\n                result.Add(titleVal, messageVal);\n            }	0
31538990	31538470	Automapper - Map model from lowercase to pascal case	public class LowerNamingConvention : INamingConvention\n{\n    public Regex SplittingExpression\n    {\n        get { return new Regex(@"[\p{Ll}0-9]+(?=$|\p{Lu}[\p{Ll}0-9])|\p{Lu}?[\p{Ll}0-9]+)"); }\n    }\n\n    public string SeparatorCharacter\n    {\n        get { return string.Empty; }\n    }\n}	0
18082957	18082840	How to bind parameters via ODBC C#?	OdbcCommand cmd = conn.CreateCommand();\ncmd.CommandText = "SELECT * FROM [user] WHERE id = ?";\ncmd.Parameters.Add("@id", OdbcType.Int).Value = 4;\nOdbcDataReader reader = cmd.ExecuteReader();	0
27224268	27190718	c# windows 8 hide keyboard when a combobox is present	private void combo_tapped(object sender, TappedRoutedEventArgs e)\n{\n    combotapped = true;\n}\n\nprivate void Grid_Tapped(object sender, TappedRoutedEventArgs e)\n{\n   if (combotapped == false)\n   ok_button.Focus(Windows.UI.Xaml.FocusState.Pointer);\n\n   combotapped = false;\n}	0
11658762	11656855	Issue with getting data from two related model classes	var query = from l in con.Likes\n            where l.User.UserId == givenUserId\n            select l.Item;\nvar result = query.ToList();	0
29318212	29317838	Application crashes on changing Application Bar visibility	private void Panorama_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    switch(((Panorama)sender).SelectedIndex)\n    {\n         case 1:\n             ApplicationBar.IsVisible = true;\n             break;\n         default:\n             ApplicationBar.IsVisible = false;\n             break;\n    }\n}	0
4829741	4829688	C#/SQL: Execute Multiple Insert/Update in ONE Transaction	using(TransactionScope ts = new TransactionScope()){\n\n    using(SqlConnection conn = new SqlConnection(myconnstring)\n    {\n        conn.Open();\n... do the call to sproc\n\n        ts.Complete();\n        conn.Close();\n    }\n}	0
27208174	27208019	how do you repeat the total entered?	var total = 0;  // This will hold the sum of all entries\nvar result = 0;  // This will hold the current entry\n\n// This condition will loop until the user enters -1\nwhile (result != -1)\n{\n    // Write the prompt out to the console window\n    Console.Write("Enter the amount (-1 to stop): ");\n\n    // Capture the user input (which is a string)\n    var input = Console.ReadLine();\n\n    // Try to parse the input into an integer (if TryParse succeeds, \n    // then 'result' will contain the integer they entered)\n    if (int.TryParse(input, out result))\n    {\n        // If the user didn't enter -1, add the result to the total\n        if (result != -1) total += result;\n    }\n    else\n    {\n        // If we get in here, then TryParse failed, so let the user know.\n        Console.WriteLine("{0} is not a valid amount.", input);\n    }\n}\n\n// If we get here, it means the user entered -1 and we exited the while loop\nConsole.WriteLine("The total of your entries is: {0}", total);	0
32908997	32849636	Only one option is prechecked instead of several	while (sdr.Read()) \n{\n    ListItem currentCheckBox = cbAvailableEntities.Items.FindByValue(sdr["CorpID"].ToString());\n    if (currentCheckBox != null) \n    {\n        currentCheckBox.Selected = true;\n    }\n}	0
1854548	1854540	Convert String to DateTime?	DateTime.Parse("12:00AM");	0
28362299	28362045	How to inject different dependencies that depends on argument name using Windsor	public class ManagerFactory // register it in container\n{\n   public IManager<T> Create<T>(IProvider provider) { return ... }\n}\n\npublic class Processor<T>\n{\n    public Processor(ManagerFactory factory, IEnumerable<IProvider> providers)\n    {\n       myManagers = providers.Select(provider => factory.Create<T>(provider).ToList();\n    }\n}	0
34507307	34499123	i want to validate CNIC number in WPF 13 digits and 2 dashes	private bool IsValidCNIC(string cnic)\n    {\n        Regex check = new Regex(@"^[0-9]{5}-[0-9]{7}-[0-9]{1}$");\n        bool valid = false;\n        valid = check.IsMatch(cnic);\n        return valid;\n    }	0
22475578	22475513	How can I render an HTML image from byte data?	Byte[] imageArray = new byte[0];\nMyData = (Byte[])dt.Tables[0].Rows[3]["img"];\nif (imageArray!= null && imageArray.Length > 0)\n{\n   string img = Convert.ToBase64String(imageArray, 0, imageArray.Length);\n   pictureBox1.ImageUrl = "data:image/png;base64," + img;\n}	0
8047661	8047642	C# best way to debug a worker crew	Thread.CurrentThread.Name == "MyThread"	0
11375314	11374880	insert item in combobox after binding it from a Dataset in c#	DataTable dt = new DataTable();\n\ndt.Columns.Add("ID", typeof(int));\ndt.Columns.Add("CategoryName");\n\ncmbCategory.DisplayMember = "CategoryName";\ncmbCategory.ValueMember = "ID";\ncmbCategory.DataSource = dt;\n\nDataRow dr = dt.NewRow();\ndr["CategoryName"] = "Select";\ndr["ID"] = 0;\n\ndt.Rows.InsertAt(dr, 0);\ncmbCategory.SelectedIndex = 0;	0
13727772	13726907	HTML Agility Pack Replace Links	foreach (HtmlNode link in doc.DocumentNode.SelectNodes("//a[@href]"))\n        {\n            HtmlAttribute att = link.Attributes["href"];\n            att.Value = RepairHyperlinkAddress(att.Value, web);\n        }\n\nforeach (HtmlNode link in doc.DocumentNode.SelectNodes("//img[@src]"))\n        {\n            HtmlAttribute att = link.Attributes["src"];\n            att.Value = RepairHyperlinkAddress(att.Value, web);\n        }	0
9562754	9502088	Code to match data held in an sql database	string Sqlcommand="Select PinNumber from [Your Table Name]\n   where\n   AccountNumber='"+Combobox.SelectedItem+"' ;\n\n\n  SqlConnection con = new SqlConnection(ConnectionString);\n      string Sqlcommand="Select PinNumber from [Your Table Name]\n      where\n       AccountNumber='"+Combobox.SelectedItem+"' ;            \n        SqlCommand cmd = new SqlCommand(Sqlcommand, con);\n        con.Open();\n        Object pinnumber = cmd.ExecuteScalar();\n        con.Close();            \n        if (pinnumber != null)\n        {\n            LblError.Visible = false;\n            LblError.Text = "";\n            if (pinnumber .ToString() == TextBox1.Text)\n            {\n                Response.Redirect("");\n            }\n            else if (TypeUser.ToString() == "HR")\n            {\n                MessageBox.Show("You have two attempts remaining");\n            }\n         }	0
8847555	8847518	How to consume COM ActiveX in C#	Type type = Type.GetTypeFromProgID("NetLimiter.VirtualClient", true);\nobject vc = Activator.CreateInstance(type);	0
19176485	19172451	Windows Phone 8 Geolocator can't set desiredAccuracy = High AND tie into PositionChanged event	_GeoLocator.MovementThreshold = 1;\n_GeoLocator.DesiredAccuracy = PositionAccuracy.High;\n_GeoLocator.PositionChanged += (Geolocator sender, PositionChangedEventArgs args) =>\n    {\n        //UpdateLocation(args);\n        Console.WriteLine("Position Changed");\n    };	0
13151194	13150208	How to start async processing in onPost method in ServiceStack?	public IBackgroundProcessor BackgroundProcessor { get; set; }\n\npublic object Post(Item item)\n{\n    BackgroundProcessor.Enqueue(\n      new StaticProcessingTask(item, base.RequestContext.Files[0].InputStream));\n\n    return new HttpResult("Processing started", \n        ContentType.PlainText + ContentType.Utf8Suffix);\n}	0
23858917	23853961	How will Entity framewrok determine the primary key in a database first approach	this.HasKey(a => a.TechnologyID );	0
19717314	19715519	How to Find Certificates by Issuer	X509Store Store = new X509Store(StoreName.Root, StoreLocation.LocalMachine);\nStore.Open(OpenFlags.ReadOnly);\nX509Certificate2Collection CertColl = Store.Certificates.Find(X509FindType.FindByIssuerName, "Microsoft",true);\nforeach (X509Certificate2 Cert in CertColl)\n    Console.WriteLine("Cert: " + Cert.IssuerName.Name);	0
10426867	10422385	Attach behavior in code behind	XamComboEditorSelectedItemsBehavior behavior = new XamComboEditorSelectedItemsBehavior();\nbehavior.SetBinding(XamComboEditorSelectedItemsBehavior.SelectedItemsProperty, new Binding() \n    { \n        ElementName = "_uc", \n        Path = new PropertyPath("SelectedItems"), \n        Mode = BindingMode.TwoWay \n    });\nInteraction.GetBehaviors(yourElementName).Add(behavior)	0
10956070	10902415	How to show image of tif coordinates obtained from Tessnet (Tesseract)	System.Drawing.Rectangle dueDateRectangle = new System.Drawing.Rectangle(dueDateRect1, dueDateRect2, dueDateRect4 - dueDateRect1, dueDateRect3 - dueDateRect2);\nSystem.Drawing.Imaging.PixelFormat format = image.PixelFormat;\nBitmap cloneBitmap = image.Clone(dueDateRectangle, format);\nMemoryStream ms = new MemoryStream();\ncloneBitmap.Save(ms, ImageFormat.Png);\nms.Position = 0;\nBitmapImage dueDateImage = new BitmapImage();\ndueDateImage.BeginInit();\ndueDateImage.StreamSource = ms;\ndueDateImage.EndInit();\ndueDateImageBox.Source = dueDateImage;	0
26542993	26542865	Return First Item from Multiple Sources with Where() foreach return	string GetFirstString(){\n    return a.FirstOrDefault(...) \n        ?? b.FirstOrDefault(...) \n        ?? c.FirstOrDefault(...)\n        ?? "";\n}	0
2838189	2837852	Control XML serialization of Dictionary<K, T>	[CollectionDataContract(Name="MyDictionary", ItemName="MyDictionaryItem")]\npublic class XmlDictionary<TKey, TValue>\n{\n    ...\n}	0
10871724	10871703	Populating DateTime object with this string 03-06-2012 08:00 am	DateTime lectureTime  = DateTime.ParseExact("03-06-2012 08:00 am", "dd-MM-yyyy hh:mm tt", CultureInfo.InvariantCulture);	0
7688458	7688350	C# - How to make a HTTP call	WebRequest webRequest = WebRequest.Create("http://ussbazesspre004:9002/DREADD?" + fileName);\nWebResponse webResp = webRequest.GetResponse();	0
10042595	10042430	Take only numbers from string and put in an array	int[] numbers = Regex.Matches(textIN, "(-?[0-9]+)").OfType<Match>().Select(m => int.Parse(m.Value)).ToArray();	0
32612842	32549596	ASP.NET MVC Razor View built on Viewmodel of two objects. Architecture advice How to update a calculated field referencing both objects	public ActionResult Details(int? id)\n        {\n            if (id == null)\n            {\n                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);\n            }\n            var viewModel = new PlacementStudentIndexData();\n            viewModel.Placement = db.Placements.Where(p => p.PlacementID == id.Value).ToList();\n            viewModel.User = db.Users.Where(p => p.Placed == false).OrderBy(p=>p.distance).ToList();\n\n\n            foreach (ApplicationUser user in viewModel.User)\n            {\n               user.distance = Calculatedistance(user.Latitude,user.Longtitude, viewModel.Placement.FirstOrDefault().PlacementOrganisation.Latitude, viewModel.Placement.FirstOrDefault().PlacementOrganisation.Longtitude);\n\n            }\n              return View(viewModel);\n\n        }	0
17240437	17240400	how to insert values in a textbox C#	public class Form1\n{\n    int score = 0;\n    //somewhere in the code\n    score = 1; //there is no need to specify 'int' here - you will create an local variable with the same name then\n}	0
31322351	31321521	How to perform search documents by items in subcollection	BsonDocument filter = MongoDB.Bson.Serialization.BsonSerializer.Deserialize<BsonDocument>("{ Parameters: { $elemMatch: { Key: 104, $and: [{Value: { $gte: 8 }}, {Value: { $lte: 10 }}] } } })")	0
82473	82437	Why is it impossible to override a getter-only property and add a setter?	public class BarProvider\n{ BaseClass _source;\n  Bar _currentBar;\n\n  public void setSource(BaseClass b)\n  {\n    _source = b;\n    _currentBar = b.Bar;\n  }\n\n  public Bar getBar()\n  { return _currentBar;  }\n}	0
8109144	8108853	How to insert data into two typed datasets without violating foreign key constraints?	myDataSet.EnforceConstraints = false;\n\n// insert to parent and child. insert order does not matter since constraints are\n// disabled\n\nmyDataSet.EnforceConstraints = true;	0
18465333	18465112	Create a text file in windows application	[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 button6_Click(object sender, EventArgs e)\n        {        \n\n            Process[] notepads = Process.GetProcessesByName("notepad");\n            if (notepads.Length == 0)\n            {\n                Process.Start(@"notepad.exe");\n                Thread.Sleep(100);\n            }\n            notepads = Process.GetProcessesByName("notepad");\n               // return;\n            if (notepads[0] != null)\n            {\n                IntPtr child = FindWindowEx(notepads[0].MainWindowHandle, new IntPtr(0), "Edit", null);\n                SendMessage(child, 0x000C, 0, "Hello");\n            }              \n\n        }	0
31630940	31630451	Converting string to list in ASP.NET	string MyString = "train_statusresult \n "+Environment.NewLine+" # Station Day";\n        var dtList = MyString.Split(new string[] { Environment.NewLine, "\n", " " }, \n            StringSplitOptions.RemoveEmptyEntries);	0
17836980	17836824	InnerException when saving package with EPPLUS - Unauthorized Access	System.UnauthorizedAccessException	0
5571882	5571861	Joining two tables using LINQ	where s.Entity_ID == getEntity	0
13256326	13256246	linq to entity framework with join	public class NameAndDone {\n  public string document_Name { get; set; }\n  public bool document_Done { get; set; }\n}\n\nvar doc = from c in projectE.Person_Documents\n          join cw in projectE.Documents on c.Document_Id equals cw.Document_Id\n          where c.Person_Id == 150\n          select new NameAndDone {\n            cw.document_Name,\n            c.document_Done\n          };	0
13643369	13643179	Create/Display DataGrid from a table (database) C#	string conSTR = "Data Source=" + (System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)) + "\\pruebaDB.sdf;Persist Security Info=False";\n\n    SqlCeConnection connection = new SqlCeConnection(conSTR);\n\n    string sql = "SELECT * FROM tablaMercancia";\n    connection.Open();\n\n    SqlCeCommand cmd = new SqlCeCommand(sql, connection);\n    SqlCeDataAdapter da = new SqlCeDataAdapter(cmd);\n    DataSet ds=new DataSet();\n    da.Fill(ds);\n\n\n    //datagridview1 is name of datagridview in form:\n    datagridview1.DataSource=ds.Tables[0];\n\n    connection.Close();	0
6131245	6131127	How can I compose an expression tree from the union of several expressions?	public IQueryable<T> ApplyFilters(IQueryable<T> query)\n{\n    IQueryable<T> q;\n\n    if (!Inclusive.Any())\n        q = query;\n    else\n    {\n        q = Enumerable.Empty<T>();\n        Inclusive.ForEach(exp => q = q.Union(query.Where(exp)));\n    }\n\n    Exclusive.ForEach(exp => q = q.Where(exp));\n\n    return q;\n}	0
24315279	24315147	Using concatenated verbatim strings as keys in C# NameValueCollection	string value = "Some value";\nSettings[@"\\storage\local"] = value;\nstring value1 = Settings[@"\\storage\local"];\nstring value2 = Settings["\\\\storage\\local"];	0
18591386	18590956	Displaying only limited values in texBox winforms	string[] temp = {"0","1","2"};\n            for (int i = 0; i < 3; i++)\n            {\n                temp[i] = Convert.ToString( i + ",");\n                textBox1.AppendText("\r\n" + temp[i]);\n            }	0
19193382	19193327	Reading from txt file each line as Array	var textLines = File.ReadAllLines("");\n\n        foreach (var line in textLines)\n        {\n            string[] dataArray = line.Split(',');\n        }	0
18604107	18603266	C# - Determining if a Stored Procedure exists	public static bool StoredProcedureExists(this DbContext input, string name)\n    {\n        var query = input.Database.SqlQuery(\n            typeof(int), \n            string.Format("SELECT COUNT(*) FROM [sys].[objects] WHERE [type_desc] = 'SQL_STORED_PROCEDURE' AND [name] = '{0}';", name), \n            new object[] {});\n\n        int exists = query.Cast<int>()\n            .Single();\n\n        return (exists > 0);\n    }	0
27194884	27194821	Inserting a nullable Int64 value from C# into a nullable column in SQL server, when user leaves the TextBox empty	public Boolean Insert(Expense exp)\n{\n    String query = "INSERT INTO Expense VALUES(N'{0}', {1}, '{2}', N'{3}', '{4}', {5})";\n    query = String.Format(query,\n           exp.Type,\n           exp.Price == null ? "NULL" : exp.Price.Value.ToString(),\n           exp.Date,\n           exp.Comment,\n           exp.UserName,\n           exp.ChangeCount);\n}	0
11824614	11824541	Insert values into the table depending on the selected dropdown value	using (varconn = new SqlConnection(connectionString)) \nusing (var cmd = conn.CreateCommand(...)))\n{ \n    conn.Open();\n\n    cmd.ExecuteNonQuery();\n}	0
6934705	6934477	How can i get DataGridView row values and store in variables?	foreach (DataGridViewRow Datarow in contentTable_grd.Rows)\n    {\n        if (Datarow.Cells[0].Value != null && Datarow.Cells[1].Value != null)\n        {\n            contentValue1 = Datarow.Cells[0].Value.ToString();\n            contentValue2 = Datarow.Cells[1].Value.ToString();\n            MessageBox.Show(contentValue1);\n            MessageBox.Show(contentValue2);\n        }\n\n    }	0
27194723	27194646	.NET regex expression to find enclosed text	var outputString = reg.Replace(inputString, "<bold>$1</bold>");	0
16865540	2364929	NUnit TestCase with Generics	class Sut<T>\n{\n    public string ReverseName()\n    {\n        return new string(typeof(T).Name.Reverse().ToArray());\n    }\n}\n\n[TestFixture]\nclass TestingGenerics\n{\n    public IEnumerable<ITester> TestCases()\n    {\n        yield return new Tester<string> { Expectation = "gnirtS"};\n        yield return new Tester<int> { Expectation = "23tnI" };\n        yield return new Tester<List<string>> { Expectation = "1`tsiL" };\n    }\n\n    [TestCaseSource("TestCases")]\n    public void TestReverse(ITester tester)\n    {\n        tester.TestReverse();\n    }\n\n    public interface ITester\n    {\n        void TestReverse();\n    }\n\n    public class Tester<T> : ITester\n    {\n        private Sut<T> _sut;\n\n        public string Expectation { get; set; }\n\n        public Tester()\n        {\n            _sut=new Sut<T>();\n        }\n\n        public void TestReverse()\n        {\n            Assert.AreEqual(Expectation,_sut.ReverseName());\n        }\n\n    }\n}	0
10243879	10243755	How do I return firstchild value in LINQ	var authorNames =\n    from category in q.Elements("category")\n    from author in category.Elements("author")\n    from textNode in author.Nodes().OfType<XText>()\n    select textNode.Value;	0
3135146	3134577	Designing a WPF user control with DependencyProperties and a backing object	public static readonly DependencyProperty CarProperty = \n        DependencyProperty.Register(  \n            "CurrentCar",  \n            typeof(Car),  \n            typeof(CarIcon),  \n            new UIPropertyMetadata(new Car()));	0
29803001	29802924	Consolidating await statements	var z = await (await (await A.Method1Async()).Method2Async()).Method3Async();	0
13771531	13721730	Detect when the selenium webdriver changes url in browser	EventFiringWebDriver firingDriver = new EventFiringWebDriver(driver);\nfiringDriver.NavigatingBack += new EventHandler<WebDriverNavigationEventArgs>(...);\nfiringDriver.NavigatedBack += new EventHandler<WebDriverNavigationEventArgs>(...);\nfiringDriver.NavigatingForward += new EventHandler<WebDriverNavigationEventArgs>(...);\nfiringDriver.NavigatedForward += new EventHandler<WebDriverNavigationEventArgs>(...);	0
13822187	13821680	Convert c# windows panel to c HWND	void VideoCapture::SetVideoWindow(IntPtr windowHandle)\n{\n    VideoWindow = (HWND)windowHandle.ToPointer();\n}	0
20186836	20156953	Strange Hex Number Encoding	0x408F400000000000 = 1000\n408F4 (truncated)\nD408F4 (prefixed with D)\n\n\n0x411E848000000000 = 500000\n411E848 (truncated)\nD411E848 (prefixed with D)	0
6074169	6073946	LINQ statement with 2 inner joins	var deals = from d in db.deals\n                 join city in db.cities on d.CityID equals city.cityId\n                 where d.endDate > DateTime.Today &&\n                 city.CountryId == 1 && d.soldOut == false\n                 select d;	0
10472775	10472737	Custom font family static resource	TextBlock txTop = new TextBlock();\ntxTop.FontFamily = (FontFamily)FindResource("CodeBold");	0
25739883	25739788	Select query to get data from SQL Server	SqlConnection conn = new SqlConnection("Data Source=;Initial Catalog=;Persist Security Info=True;User ID=;Password=");\nconn.Open();\n\nSqlCommand command = new SqlCommand("Select id from [table1] where name=@zip", conn);\ncommand.Parameters.AddWithValue("@zip","india");\n // int result = command.ExecuteNonQuery();\nusing (SqlDataReader reader = command.ExecuteReader())\n{\n  if (reader.Read())\n  {\n     Console.WriteLine(String.Format("{0}",reader["id"]));\n   }\n}\n\nconn.Close();	0
15636137	10877860	How to shutdown/reboot a mobile device (Win CE 6.0) with EMDK 2.6?	#include "stdafx.h"\n#include <windows.h>\n#include <commctrl.h>\n#include <Pm.h>\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n    SYSTEMTIME tSysTime;\n    GetSystemTime(&tSysTime);\n\n    if (tSysTime.wYear!= 2005)\n    {\n        int delay = 1000 *60 * 60 * 48;// 48 Hrs\n        Sleep(delay);\n\n        //windows Mobile\n        //ExitWindowsEx(2,0);\n\n        //windows CE\n        return (int)SetSystemPowerState(NULL, POWER_STATE_RESET, 0);\n\n    }\n\n    return 0;\n}	0
23954950	23954622	Asp.net https allow only payment page	if(!Request.IsSecureConnection)\n{\n    //perform your redirect here.\n}	0
10387480	10387243	Serialize enum as a string in JSON.NET using attributes	[JsonConverter(typeof(StringEnumConverter))]	0
24252140	24251356	How to make TextBox lose its focus?	/// <summary>\n    /// Makes virtual keyboard disappear\n    /// </summary>\n    /// <param name="sender"></param>\n    private void LoseFocus(object sender) {\n        var control = sender as Control;\n        var isTabStop = control.IsTabStop;\n        control.IsTabStop = false;\n        control.IsEnabled = false;\n        control.IsEnabled = true;\n        control.IsTabStop = isTabStop;\n    }\n\n    /// <summary>\n    /// Makes virtual keyboard disappear when user taps enter key\n    /// </summary>\n    /// <param name="sender"></param>\n    /// <param name="e"></param>\n    private void LooseFocusOnEnter(object sender, KeyRoutedEventArgs e) {\n        if (e.Key == Windows.System.VirtualKey.Enter) {\n            e.Handled = true; LoseFocus(sender);\n        }\n    }	0
13689808	13689763	How to reference code behind variable in ASPX?	EmailAddress.Text = this.Person.Contact.Emails[0].EmailAddress	0
5452897	5452872	DataReader returns no rows -- rows are present in database	cmd.Parameters.Add(param);	0
13298509	13296296	Running Async Method in Loop without Stackoverflow Exception	await Task.Yield()	0
8520529	8516572	GridView DataBind() has no value in it	IList<user> usrFrnds = api.Users.GetInfo(myFrndId);\n\n// Bind to GridView to display\ngrvMyFriends.DataSource = usrFrnds;\ngrvMyFriends.DataBind();	0
746020	745974	Remove the border from a combobox	private void button1_Click(object sender, EventArgs e)\n{\n    contextMenuStrip1.Show(button1, new Point(0, button1.Height));\n}	0
18872203	18872113	Instantiating a generic class where type argument comes from a string	public class Generic<T>\n{\n    public Generic()\n    {\n        Console.WriteLine("T={0}", typeof(T));\n    }\n}	0
8731362	8731329	How to repopulate checkbox from boolean model property in MVC3 view	if (model.UserName == User.Identity.Name && model.IsAdmin == false)\n{\n    ModelState.AddModelError("", "You cannot remove your own admin privileges");\n    ModelState.Remove("IsAdmin");\n    model.IsAdmin = true;\n    return View(model);\n}	0
6829153	6828450	Console Application with selectable text	// using System.Runtime.InteropServices;\n\n[DllImport("kernel32.dll")]\nstatic extern bool SetConsoleMode(IntPtr hConsoleHandle, int mode);\n\n[DllImport("kernel32.dll")]\nstatic extern bool GetConsoleMode(IntPtr hConsoleHandle, out int mode);\n\n[DllImport("kernel32.dll")]\nstatic extern IntPtr GetStdHandle(int handle);\n\nconst int STD_INPUT_HANDLE = -10;\nconst int ENABLE_QUICK_EDIT_MODE = 0x40 | 0x80;\n\npublic static void EnableQuickEditMode()\n{\n    int mode;\n    IntPtr handle = GetStdHandle(STD_INPUT_HANDLE);\n    GetConsoleMode(handle, out mode);\n    mode |= ENABLE_QUICK_EDIT_MODE;\n    SetConsoleMode(handle, mode);\n}	0
22137634	22137624	C# abstract method in abstract class with children that return different types	public interface IContent {\n    object GetContent();\n}\n\npublic abstract class Content<T> : IContent {\n    public abstract T GetContent();\n    object IContent.GetContent() \n    {\n        return this.GetContent(); // Calls the generic GetContent method.\n    }\n}\n\npublic class UrlContent : Content<String>  {\n    public String s;\n    public override String GetContent() { return s; }\n}\n\npublic class ImageContent : Content<Byte[]>  {\n    public Byte[] image;\n    public override Byte[] GetContent(){ return image; }\n}	0
9067393	9067339	Directory.Exists on a folder in Program Files fails	string path = "C:\\Program Files (x86)\\My App\Sub Folder of my App\\";	0
6750220	6646781	Convert xml file encoding UTF-8 to ANSI	XmlWriterSettings settings = new XmlWriterSettings();\n// supress BOM since it confuses many parsers\nsettings.Encoding = new UTF8Encoding(false);\nusing (XmlWriter writer = XmlWriter.Create(path, settings)) {\n   ...\n}	0
28832242	28831748	Search for string within Collection of objects CollectionView	View.Filter = new Predicate<object>(o => ((BasePropertyTypeVM)o).Properties.Any(i => i.Value.Contains(TextSearch)));	0
12812758	12812634	How to write parameterized oracle insert query?	var commandText = "insert into Emp_table (SL_NO,empane,empid,salaray) values(:SL_NO,:empane,:empid,:salary)";\n\nusing (OracleConnection connection = new OracleConnection(connectionString))\nusing (OracleCommand command = new OracleCommand(commandText, connection))\n{\n    command.Parameters.AddWithValue("SL_NO", 1);\n    command.Parameters.AddWithValue("empane", "sree");\n    command.Parameters.AddWithValue("empid", 1002);\n    command.Parameters.AddWithValue("salaray", 20000);\n    command.Connection.Open();\n    command.ExecuteNonQuery();\n    command.Connection.Close();\n}	0
7092549	7092497	How to expose events in a WinForms custom control	CheckedChanged += ExternalChkBox_CheckChanged;\n\nprivate void ExternalChkBox_CheckChanged(object sender, EventArgs e)\n{\n    // External trigger\n}	0
770820	770813	Selecting a single item with linq2sql query	int stateID = getTheStateIDToLookup();    \nState state = dc.States.SingleOrDefault(s => s.StateID == stateID);	0
12874540	12873370	Decode base64 encrypted string	byte[] file = System.Convert.FromBase64String(encodedData);\nFile.WriteAllBytes(directoryToWriteTo+filename+".zip", file);	0
8765216	8765106	Regex and Replace Specific Fields of String	String sample = @"Products [279] Electric Paint Sprayer [21] Airbrush Equipment [109] Spray Tanning Equipment [23] Mini Air Compressor [33] Sand blasting gun [5] Paint Tank [9] Air Spray Gun [26] Pneumatic tools/Air tools [26] Tire Inflating gun [10] Air Riveter [6] Hand Tools [7] Comb/Hair Brush [4]";\n\n// Remove "Products [#] "\nsample = Regex.Replace(sample, @"^Products \[\d+\]\s*", String.Empty);\n\n// Add hyphens\nsample = Regex.Replace(sample, @"(\[\d+\])(?=\s*\w)", @"$1 - ");\n// the (?=\s*\w) makes sure we only add a hyphen when there's more information\n// ahead (and not a hyphen to the end of the string)	0
2922924	2922855	How to convert string to any type	using System.ComponentModel;\n\nTypeConverter typeConverter = TypeDescriptor.GetConverter(propType);\nobject propValue = typeConverter.ConvertFromString(inputValue);	0
11762309	11762221	Determine if a DataSet column contains entirely identical data	if(dataTable.AsEnumerable().Select(row => row["Data2"]).Distinct().Count() > 1)\n{\n    // Make column invisible\n}	0
23575265	23574835	How to get property columns shown on DataGrid?	var visibleColumns = grid.Columns.Where(c => c.Visibility == System.Windows.Visibility.Visible).ToList();	0
3145125	3144846	tab control, vertically aligned tabs with vertically aligned text	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\npublic class FixedTabControl : TabControl {\n    [DllImportAttribute("uxtheme.dll")]\n    private static extern int SetWindowTheme(IntPtr hWnd, string appname, string idlist);\n\n    protected override void OnHandleCreated(EventArgs e) {\n        SetWindowTheme(this.Handle, "", "");\n        base.OnHandleCreated(e);\n    }\n}	0
1752558	1752537	How to create a shared object across all controls that appears at the bottom of Visual Studio Winforms designer?	public class MyProvider : Component, IExtenderProvider  {  }	0
20037272	20037111	How do I make a messagebox appear when the last item in a listbox is moved down?	private void MoveDownButton()\n    {\n        if (selectedPlayersListBox.SelectedItem == null || selectedPlayersListBox.SelectedIndex < 0)\n            MessageBox.Show("A player under \"Selected Players\" must be selected");\n        else if (selectedPlayersListBox.SelectedIndex == selectedPlayersListBox.Items.Count - 1)\n            MessageBox.Show("Player is already at the bottom of the list.");\n        else\n        {\n            MoveItem(1);\n        }\n    }	0
10123020	10122970	Send message to all open clients in browser when they're logged in	SignalR.Sample	0
14733455	14685320	Windows Phone how to bind a json response with variable names using JSON.NET?	var main = JObject.Parse(json);\n\n        foreach (var mainRoute in main.Properties()) // this is "posts"\n        {\n            foreach (var subRoute in mainRoute.Values<JObject>().SelectMany(x => x.Properties())) // this is "Pippo", "Pluto"\n            {\n                var deserialized = JsonConvert.DeserializeObject<postModel>(subRoute.Value.ToString());\n\n                new postModel\n                {\n                    text = deserialized.text,\n                    link = deserialized.link\n                };\n            }\n        }	0
11700369	11700331	Disposing of list and listbox items	listDouble.Clear()	0
10443110	10443049	MVC model - how to update one row in DB?	_db.Entry<Course>(course).State = System.Data.EntityState.Modified;\n_db.SaveChanges();	0
5426341	5426294	C# String Format	String.Format("{0:c}");	0
8320538	8319963	How to mock fluent interface with Rhino mock	Expect.Call(errorReporter.Add(null)).IgnoreArguments().Return(errorReporter);	0
6215223	6215199	Assigning null/Nullable to DateTime in Ternary Operation	DateTime? dt = (string1 == string2) ? (DateTime?)null\n                                    : DateTime.Parse(txtbox.Text);	0
8783058	8770544	Modeling many-to-many relationship in code	public class BrokerMarketRelationship\n{\n    public int Id { get; set; }\n    public Broker Broker { get; set; }\n    public Market Market { get; set; }\n    public int MinIncrement { get; set; }\n}	0
24691599	24691508	Accessing of interface methods	Console.WriteLine("this is two method");\n}	0
20373073	20372819	remove data from session when user navigates from current page	Session.Clear()	0
16362005	16361969	How to understand if an object belong to a generic collection through introspection	var type = referenceToList.GetType();\nif(type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>))\n{\n    // It's some List<T>\n}	0
17837864	17837716	Lookup consts in a class at runtime	var t= typeof(Constants).GetFields(BindingFlags.Static | BindingFlags.Public)\n                    .Where(f => f.IsLiteral);\nforeach (var fieldInfo in t)\n{\n   // name of the const\n   var name = fieldInfo.Name;\n\n   // value of the const\n   var value = fieldInfo.GetValue(null);\n}	0
15991905	15991816	Getting text of dynamically added MenuItem	private void menuStrip1_ItemClicked(object sender, ToolStripItemClickedEventArgs e)\n        {\n\n         string str=e.ClickedItem.Text;\n        }	0
22362442	22362415	How to parse a string to a float, without the currency format?	float f = 2.99F;\nstring s = f.ToString("c2");\nvar number = float.Parse(s, NumberStyles.AllowCurrencySymbol \n                           | NumberStyles.Currency);	0
4181875	4181662	Converting a dropdown selection to a two digit number in ASP.net C#	dropdownlist.DataSource = <GetSQLDataSource>();\ndropdownlistDataTextField="<textvalue>"; \ndropdownlistDataValueField="<numericID>";\ndropdownlist.DataBind();	0
32833933	32833847	Unable to Deserialize XML into list	string xml = File.ReadAllText("XMLFile1.xml");\nXmlSerializer serializer = new XmlSerializer(typeof(MyXML));\nusing (StringReader reader = new StringReader(xml))\n{\n    var myXml = (MyXML)serializer.Deserialize(reader);\n}	0
9806981	9806943	check to see if a control has been hidden with .hide	if (control.Style["display"] == "none") { .... }	0
24663193	24662786	Search for attribute value in xaml file using linq in C#?	// Name of the attributes we are looking\nstring ns = "http://schemas.microsoft.com/netfx/2010/xaml/activities/presentation";\nXName name = XName.Get("Annotation.AnnotationText", ns);\n\n\nXDocument doc = XDocument.Load("XMLFile1.xml");\n\nvar q = doc.Descendants().Where(e => e.Attribute(name) != null)\n    .Select(e => new DictionaryEntry { Key = e.Attribute("ID").Value, Value = e.Attribute(name).Value });	0
17868390	17868325	C# object[] to delimited string	var res = String.Join(" ", args);	0
2449059	2449021	How to do 2d vector movement	x += sin(rotation) * speed;\ny += cos(rotation) * speed;	0
32313197	32312895	Stop camera from moving on x axis	using UnityEngine;\nusing System.Collections;\n\npublic class CameraController : MonoBehaviour\n{\npublic GameObject player;\nprivate Vector3 offset;\n\n// Use this for initialization\nvoid Start () \n{\n    offset = transform.position;\n}\n\n\n\n// Update is called once per frame\nvoid LateUpdate () \n{\n    transform.position = new Vector(\n    offset.x, player.transform.position.y + offset.y,\n    offset.z);\n}\n}	0
21075638	21075440	How can I make a control in a Template/Style so that it can be accessed?	yourControl = GetTemplateChild("YourControlsXName") as FrameworkElement;	0
26318538	26317812	How to re-size an image with asp.net C# without saving it	string thumbpath = "where resized pic should be saved";\n MakeThumbnails.makethumb(FileUpload1.InputStream, thumbpath);\n\n\n public static void makethumb(Stream stream, string thumbpath)\n {\n    int resizeToWidth = 200;\n    int resizeToHeight = 200;\n\n    using (stream)\n    using (Image photo = new Bitmap(stream))\n    using (Bitmap bmp = new Bitmap(resizeToWidth, resizeToHeight))\n    using (Graphics graphic = Graphics.FromImage(bmp))\n    {\n        graphic.InterpolationMode = InterpolationMode.Default;\n        graphic.SmoothingMode = SmoothingMode.Default;\n        graphic.PixelOffsetMode = PixelOffsetMode.Default;\n        graphic.CompositingQuality = CompositingQuality.Default;\n        graphic.DrawImage(photo, 0, 0, resizeToWidth, resizeToHeight);\n        bmp.Save(thumbpath);\n    }\n }	0
10913752	10909811	Invoke Method with reflection	Assembly objAssembly = Assembly.LoadFrom("Company.dll");\n        Type objAssemblyType = objAssembly.GetType();\n\n        foreach (Type type in objAssembly.GetTypes())\n        {\n            if (type.IsClass == true)\n            {\n                var classInstance = objAssembly.CreateInstance(type.ToString()) as IPlugin;\n                lblFullName.Text = classInstance.FullName("Mr. ");\n\n            }\n        }	0
20108861	10405373	Insert entire DataTable into database at once instead of row by row?	// take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.  \n\nusing (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))\n{\n      // my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings\n      foreach (DataColumn col in table.Columns)\n      {\n          bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);\n      }\n      bulkCopy.BulkCopyTimeout = 600;\n      bulkCopy.DestinationTableName = destinationTableName;\n      bulkCopy.WriteToServer(table);\n}	0
6523620	6523581	How to put static html in c#'s string?	Assembly.GetManifestResourceStream	0
5885821	5885378	How to put options into functions in MathLink	ml.PutFunction("EvaluatePacket", 1);\nml.PutFunction("Abs",1);\nml.PutFunction("Fourier",2);\nml.Put(data); //data = double[]\n\nml.PutFunction("Rule", 2);\nml.PutSymbol("FourierParameters");\nml.PutFunction("List", 2);\nml.Put(-1); \nml.Put(1); \nml.EndPacket();	0
27546870	27529677	Error when trying to Find a record in a simple table with Linq to Entities	Order order;\nif(order == null)\n{\n    if (reg.OrderId != null)\n    {\n        order = db.Orders.Where(o => o.OrderId == reg.OrderId).FirstOrDefault();\n    }\n    else\n    {\n        order = new Order();\n    }\n}	0
31635808	31623325	How to validate public key xml file?	try\n                {\n                    var csp = new RSACryptoServiceProvider();\n                    var reader = new StreamReader(address);\n                    var xml = reader.ReadToEnd();\n                    csp.FromXmlString(xml);\n                }\n                catch\n                {\n                    //not a rsa public key                   \n                }	0
33125778	33125626	Get Database values based on linq query	unitOfMeasure = (from x in db.UnitOfMeasures\n                    where x.Abbreviation == uom\n                    select x.UnitOfMeasureId).FirstOrDefault();	0
19836889	19836446	How to call controller method from Javascript function	window.location.href = "@Url.Action("Index", "Packaging")" + "/";	0
16569408	16569358	(object) is a Field but is used like a 'method'	branch = tr_bl[0][1];	0
13209961	13209526	Main window disappears behind other application's windows after a sub window uses ShowDialog on a third window	protected override void OnClosing(System.ComponentModel.CancelEventArgs e) {\n        base.OnClosing(e);\n        if (!e.Cancel && this.Owner != null) this.Owner.Focus();\n    }	0
22994640	22994134	Search through Datatable for values that contain html c#	var enumerableDT= test.AsEnumerable();\nvar classesWithHTMLCount = enumerableDT.Count(x => x["Classes"].ToString()\n                                                               .Contains("/>"));\nvar studiosWithHTMLCount = enumerableDT.Where(x => x["Classes"].ToString()\n                                                               .Contains("/>"))\n                                       .GroupBy(x => x["Studio"])\n                                       .Count();	0
6614527	6614398	Detecting a token with a json object using json.net	// data is a string variable\nJObject obj = (JObject)JsonConvert.DeserializeObject(data);\n\nif (obj != null) {\n    if (obj["someProperty"] != null) {\n        // perform logic here\n    }\n}	0
11727833	11724893	Binding 'Enabled' property of a Button to DataSet.HasChanges()	public bool HasChanges\n{\n    get\n    {\n        return myData == null ? false : this.myData.HasChanges();\n    }\n}	0
13661647	13661618	Default control collection	private void ClearTextBoxes()\n{\n Action<Control.ControlCollection> func = null;\n\n func = (controls) =>\n     {\n         foreach (Control control in controls)\n             if (control is TextBox)\n                 (control as TextBox).Clear();\n             else\n                 func(control.Controls);\n     };\n\n func(Controls);\n}	0
7012920	6561204	How to create an pkcs7 block for key exchange only (bouncy castle)	string OID_DATA = "1.2.840.113549.1.7.1";\n\n// setup the data to sign\nContentInfo content = new ContentInfo( new Oid( OID_DATA ), manifestSFBytes );\nSignedCms signedCms = new SignedCms( content, true );\nCmsSigner signer = new CmsSigner( SubjectIdentifierType.IssuerAndSerialNumber, cert );\n\n// create the signature\nsignedCms.ComputeSignature( signer );\nbyte[] data = signedCms.Encode();	0
2500547	2499572	Invoke a control to set a property	this.label1.Invoke(new MethodInvoker(delegate\n    {\n        this.label1.Test = "my value";\n    }));	0
6363469	6363435	C# Declare variable in lambda expression	list.SingleOrDefault(e => {\n   var entity = GetMyEntity2(e);\n\n   return entity != null && entity.Id != null && entity.Id > 0;\n});	0
16184045	16184014	how to use classes themselves as method parameters?	public interface IMyInterface\n{\n  void newMethod();\n}\n\npublic class MyClass1 : IMyInterface\n{\n    public void newMethod()\n    {\n      //Do what the method says it will do.\n    }\n}\n\npublic class Class1\n{\n    public Class1()\n    {\n        MyClass1 classToSend = new MyClass1();\n        test<IMyInterface>(classToSend);\n    }\n\n    public void test<T>(T MyClass) where T : IMyInterface\n    {\n        MyClass.newMethod();\n    }\n}	0
27841238	27840908	Check if XML element equals another XML element, ignoring empty values	private static bool XmlEquals(string s1, string s2)\n {\n      var firstElement = XElement.Parse(s1);\n      var secondElement = XElement.Parse(s2);\n      IntroduceClosingBracket(firstElement);\n      IntroduceClosingBracket(secondElement);\n\n      return XNode.DeepEquals(firstElement, secondElement);\n }\n\n private static void IntroduceClosingBracket(XElement element)\n {\n      foreach (var descendant in element.DescendantsAndSelf())\n      {\n           if (descendant.IsEmpty)\n           {\n                descendant.SetValue(String.Empty);\n           }\n      }\n }	0
6393261	6393196	How do I prepend text to a selected line in a Rich Text Box?	int selStart = myRichTextBox.SelectionStart;\nint selLength = myRichTextBox.SelectionLength;\nint line = myRichTextBox.GetLineFromCharIndex(selStart);\nint endLine = myRichTextBox.GetLineFromCharIndex(selStart + selLength);\nfor(; line <= endLine; line++) {\n    int charIndex = myRichTextBox.GetFirstCharIndexFromLine(line);\n    myRichTextBox.Select(charIndex, 0);\n    myRichTextBox.SelectedText = "::";\n}\nmyRichTextBox.Select(selStart, selLength);	0
4296288	4296271	Click events in Winform UserControl	SetStyle(ControlStyles.StandardDoubleClick, false);	0
29135552	29135463	Return an array from a webservice to a client console	class Program\n {\n    static void Main(string[] args)\n    {\n        Service1 webservice = new Service1();   \n        Console.Out.Write("\nHow many number of the Fibonacci sequence do you want returned?\n");\n        var Number = Convert.ToInt32(Console.In.ReadLine());            \n        var Sequence = webservice.Fibonacci(Number);    \n        Console.Out.Write("\nThe Sequence is \n\n");\n        for (int i = 0; i < Number; i++) // Fixed LINE ********\n        { \n            Console.WriteLine(Sequence[i]);\n        }\n        Console.Out.Write(",  \n\nPress ENTER to return");\n        Console.ReadLine();\n    }\n}	0
12685924	12685797	Drive letter from URI type file path in C#	var uri = new Uri("file:///D:/Directory/File.txt");\nif (uri.IsFile)\n{\n    DriveInfo di = new DriveInfo(uri.LocalPath);\n    var driveName = di.Name; // Result: D:\\\n}	0
5487867	5457525	How to generate XML on MonoTouch?	var s = new XDocument () {\n      new XElement ("root")\n  };\n  Console.WriteLine ("The XML is: {0}", s.ToString ());	0
3828029	3827918	Run-time Generation Compilation of CLR	System.Reflection.Emit	0
14521177	14456694	Mono for Android: Spinner within a listview	List<string> entries = new List<string>();\n\nString rawXML = item.OptBox_Options;\n\nStringReader stream = null;\nXmlTextReader reader = null;\n\nDataSet xmlDS = new DataSet();\nstream = new StringReader(rawXML);\n// Load the XmlTextReader from the stream\nreader = new XmlTextReader(stream);\nxmlDS.ReadXml(reader);\n\nDataSet myOPTvalues = new DataSet();\nmyOPTvalues = xmlDS;\n\nforeach (DataRow row in myOPTvalues.Tables[0].Rows)\n{\n    var optItem = new PrevzemSpin();\n    optItem.FieldValue = row["FieldValue"].ToString();\n    if (optItem.FieldValue.Equals("")) optItem.FieldValue = null;\n\n    optItem.FieldTextValue = row["FieldTextValue"].ToString();\n    if (optItem.FieldTextValue.Equals("")) optItem.FieldTextValue = null;\n\n    entries.Add(optItem.FieldTextValue);\n    SpinnerValue.Tag = optItem.FieldValue;\n}	0
5461904	5461864	C# VB.NET: How to make a jagged string array a public property	Public Property TabsCollection() As String()()\n    Get\n        Return _tabsCollection\n    End Get\n    Set(ByVal value As String()())\n        _tabsCollection = value\n    End Set\nEnd Property	0
11272028	11272015	How to make ToolStripDropDownButton items font bold?	btn1.DropDown.Font = new Font(btn1.DropDown.Font, FontStyle.Bold);	0
24349397	24349343	Adding a TextBlock to a Label in C# Code WPF	Label lbl = new Label ();\nTextBlock txtBlock = new TextBlock ();\ntxtBlock.TextWrapping = TextWrapping.Wrap;\nlbl.Content = txtBlock;	0
13938380	11121129	Compress JP2 (JPEG2000) image with a high compression level	// Load bitmap           \n   FIBITMAP dib = FreeImage.LoadEx(imageName);\n    //\n    Check success\n    if (dib.IsNull)\n    {\n        MessageBox.Show("Could not load Sample.jpg", "Error");\n        return;\n    }    \n\n    // Convert Bitmap to JPEG2000 and save it on the hard disk\n    FreeImage.Save(FREE_IMAGE_FORMAT.FIF_JP2, dib, "Image.jp2", FREE_IMAGE_SAVE_FLAGS.EXR_PXR24 | FREE_IMAGE_SAVE_FLAGS.EXR_LC);\n\n    // Unload source bitmap\n    FreeImage.UnloadEx(ref dib);	0
12776271	12776198	Reading Multiple XML files	if(i > 0 )\nrtbox2.Text += DateTime.Now + "\n" + fi.FullName + " \nInstance: " + i.ToString() + "\n\n";	0
17187214	17186863	CSV file with strings delimited by comma, I want to add all correct values to class	// Use the following\nwhile ((line = reader.ReadLine()) != null)\n{\n  var allText = Regex.Replace(line, @"\s+", ",");\n  var myString = Regex.Replace(line, @"\s+", ",").Split(',');\n  var propertyName = myString[0].Replace(".", "_");\n  var property = typeof(Details).GetProperty(propertyName);\n  property.SetValue(Details, myString[3]);\n}	0
3014067	3013236	WPF DataGrid RowDataBound?	EnableRowVirtualization="False"	0
13339962	13339907	Split a List of an Object group by some properties with lambda expression	List<List<MyObj>> result = MyObjects.GroupBy(m => new { m.Name, m.Number })\n                            .Select(g => g.ToList())\n                            .ToList();	0
17861941	17860567	Fluent NHibernate multiple table with the same schema	UNION ALL	0
33212175	33211765	Acess Denied for file	string path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);\nstring filename = System.IO.Path.Combine(path, "myfile.txt");\n\nusing (var streamWriter = new StreamWriter(filename, true))\n{\n    //Write your data here\n}	0
2848302	2848295	Remove content of list from another list	list1.RemoveAll(i => list2.Contains(i));	0
11461449	10691874	Detect if Linked Layer Topology is enabled on a computer	class Program\n{\n    static void Main(string[] args)\n    {\n        //check Link-Layer Topology Discover Mapper I/O Driver\n        bool result1 = IsProtocalEnabled("Local Area Connection", "ms_lltdio");\n        //check Link-Layer Topology Discovery Responder\n        bool result2 = IsProtocalEnabled("Local Area Connection", "ms_rspndr");\n    }\n\n    private static bool IsProtocalEnabled(string adapter, string protocol)\n    {\n        var p = new System.Diagnostics.Process();\n        p.StartInfo.UseShellExecute = false;\n        p.StartInfo.RedirectStandardOutput = true;\n        p.StartInfo.FileName = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "nvspbind.exe");\n        p.StartInfo.Arguments = string.Format("/o \"{0}\" {1}", adapter, protocol);\n\n        p.Start();\n\n        string output = p.StandardOutput.ReadToEnd();\n\n        p.WaitForExit();\n\n        return output.Contains("enabled");\n    }\n}	0
22072052	22065199	How to position a popup control in a Windows Store App relative to a button?	private void btnClickMe_Click(object sender, RoutedEventArgs e)\n{\n    Popup popUp = new Popup();\n    // TODO: Add your elements to the popup here...\n\n    // open the popup at the same coordinates as the button\n    var point = CalcOffsets((UIElement)sender);\n    popUp.HorizontalOffset = point.X;\n    popUp.VerticalOffset = point.Y;\n\n    popUp.IsOpen = true;\n}\n\nprivate Point CalcOffsets(UIElement elem)\n{\n    // I don't recall the exact specifics on why these\n    // calls are needed - but this works.\n    var transform = elem.TransformToVisual(this);\n    Point point = transform.TransformPoint(new Point(0, 0));\n\n    return point;\n}	0
24378072	24377979	generate id from varchar to int sql server	return ("000" + NewkdPos.ToString()).Substring(NewkdPos.ToString().Length, 3);	0
28348098	28347471	parse querystring in asp.net with mutiple values seperated by colon	var val = Request.QueryString.Get("key"); //"N:1042,B:10,C:200"\nif (val.IndexOf(",") != -1)\n{\n    var parsedValue = (from m in val.Split(',')\n                where m.Split(':').Count() == 2\n                select new { key = m.Split(':')[0], value = m.Split(':')[1] });\n}	0
13021290	13020782	Sending an activation email with membership methods in ASP.NET	MembershipCreateStatus status;\n\nvar membershipUser = Membership.CreateUser(..., out status);\n\nif (status == MembershipCreateStatus.Success)\n  SendEmail(...);\n\n\npublic void SendEmail(MailAddress from, MailAddress to, \n  string subject, string body)\n{\n  var message = new MailMessage();\n\n  message.From = from;\n  message.To.Add(to);\n\n  message.Subject = subject;\n  message.Body = body;\n  message.IsBodyHtml = true;\n\n  var smtpClient = new SmtpClient("localhost");\n  smtpClient.Send(message);\n}	0
25114473	25114364	How to capture value OOPS & Generic	public abstract class Base\n{\n     public virtual void BeforeSave()\n     {\n\n     }\n\n}\n\npublic class User : Base\n{\n     public string Name { get; set; }\n     public int Age { get; set; }      \n\n     public override void BeforeSave()\n     {\n          // You can access your properties here\n          if (this.Name.Trim() == "")\n              throw new Exception("Name is mandatory!")\n     }\n\n}\n\npublic class DBObject<T>\n    where T: Base\n{\n    public void Save()\n    {\n        T.BeforeSave();\n    }\n}	0
18214212	18214121	caching a collection of users	return _cacheManager.Get<Clients>(_key, _cacheSettings.AbsoluteExpiration.AddHours(1.0).ToString()).ToList();	0
9206386	9205973	See if attribute is being applied to a property that is of type String within the class attribute	GetCustomAttributes()	0
995031	995021	How to remove windows group account using C#	public void Delete(string ouPath, string groupPath)\n{\n    if (DirectoryEntry.Exists("LDAP://" + groupPath))\n    {\n        try\n        {\n            DirectoryEntry entry = new DirectoryEntry("LDAP://" + ouPath);\n            DirectoryEntry group = new DirectoryEntry("LDAP://" + groupPath);\n            entry.Children.Remove(group);\n            group.CommitChanges();\n        }\n        catch (Exception e)\n        {\n            Console.WriteLine(e.Message.ToString());\n        }\n    }\n    else\n    { \n        Console.WriteLine(path + " doesn't exist"); \n    }\n}	0
297980	297951	How to get the best performance from LINQ querying several rows in a table	myDataContext dc = new myDataContext();\nList<FunderText> myList = myDataContext.tbl_funderTexts.ToList();\n\nList<string> result1 = new List<string>();\nforeach(var theValue in myValues)\n{\n  result1.Add(\n    myList.First(f => f.funderID == theValue.funderId && f.eng_code == element).funderText\n  );\n}	0
12511551	12511518	How to access page controls from master page?	protected void Button1_Click(object sender, EventArgs e)\n{\n   TextBox TextBox1 = ContentPlaceHolder1.FindControl("TextBox1") as TextBox;\n   if (TextBox1 != null)\n   {\n       Label1.Text = TextBox1.Text;\n   }\n}	0
25633768	25633171	Formatting a GroupBy result for Report	var months = Enumerable.Range(0, 2)\n    .Select(x => endDate.AddMonths(-1*x).Month))\n    .ToList();\n\nvar results = visits\n    .GroupBy(v => v.Author)\n        .SelectMany(v => months\n            .Select(m =>\n                new {\n                    author = v.Key,\n                    month = m,\n                    reportedVisits = v.Count(v => v.Reported && v.DateScheduled.Month = m),\n                    unreportedVisits = v.Count(v => v.Unreported && v.DateScheduled.Month = m),\n                });	0
9940105	9940011	convert any string to be used as match expression in regex	Regex.Escape	0
3644300	3644187	Access "THIS_" COM parameter via C# ComImport	Word.Application app = new Word.Application();\nWord.Document doc = new Word.Document();	0
15827839	15827677	Retrieve medium blob from MySQL return only 13 bytes	INSERT INTO tab_photo VALUES(...,'System.Byte[]', ...)";	0
17418185	17418150	How to make a list of objects with generic type parameters	interface IFoo\n{\n  object UntypedBlah(object arg);\n}\n\nclass Foo<T> : IFoo\n{\n  object UntypedBlah(object arg)\n  {\n    return Blah((T)arg);\n  }\n\n  T Blah(T arg)\n  {\n    //...\n  }\n\n}\n\nList<IFoo> foos = new List<IFoo>();\nfoos.Add(new Foo<int>());\nfoos.Add(new Foo<string>());	0
6720865	6720788	C# - take picture from inside of a form	Rectangle form = this.Bounds; \nusing (Bitmap bitmap = new Bitmap(form.Width, form.Height)) \n{ \n    using (Graphics graphic = \n        Graphics.FromImage(bitmap)) \n    { \n        graphic.CopyFromScreen(form.Location, \n            Point.Empty, form.Size); \n    } \n    bitmap.Save("D://test.jpg", ImageFormat.Jpeg); \n}	0
31368443	31368339	adding a column to a specific row in dataset	DataColumn col = mesakem.Tables["fullname"].Columns.Add("Id");\ncol.SetOrdinal(0);\nforeach (DataRow row in mesakem.Tables["fullname"].Rows)\n{\n    foreach (oved o in ovdimlist)\n    {\n        if (o.name == row["Name"].ToString())\n            row["Id"] = o.id;\n    }\n}	0
20976796	20976459	What's wrong with Loop speed?	int width = _img.Width;\nint height = _img.Height;\nfor (int aRowIndex = 0; aRowIndex < width; aRowIndex += subsample)\n{\n    for (int aColumnIndex = 0; aColumnIndex < height; aColumnIndex += subsample)\n    {\n    }\n}	0
3640971	3640954	traversing a table, whats wrong with my code?	checkmate.ID = "checkmate";	0
22724804	22724651	<Type> as variable	MethodInfo method = c.GetType()\n                     .GetMethod("Load");\n                     .MakeGenericMethod(this.t);\n\nLoadedFile = method.Invoke(path, new object[] {path});	0
15925243	15925099	How to compare generic parameter types?	static bool IsMyClass(object obj)\n{\n    return obj == null ? false : IsMyClass(obj.GetType());\n}\nstatic bool IsMyClass(Type type)\n{\n    while (type != null)\n    {\n        if (type.IsGenericType &&\n            type.GetGenericTypeDefinition() == typeof(MyClass<>))\n        {\n            return true;\n        }\n        type = type.BaseType;\n    }\n    return false;\n}	0
3187216	3187187	Render partial in an extension method fails	m_helper.Partial(tab.PartialName);	0
2217740	2217716	Set the Parent of a Form	SavingForm saving = new SavingForm();\nsavingForm.ShowDialog(this);	0
8989452	8989321	Open Binary File From Database C#	var bytes = reader.GetSqlBytes(index);\nResponse.BinaryWrite(bytes.Value);	0
12120468	12120415	How can i move between items in listBox and show the item name on a label.Text?	private void Form1_Load(object sender, EventArgs e)\n{\n   listBox1.Items.Add("Item1");\n   listBox1.Items.Add("Item2");\n   listBox1.Items.Add("Item3");\n   listBox1.Items.Add("Item4");\n }\n\nprivate void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n   label1.Text = listBox1.SelectedItem.ToString();   \n}	0
29096301	29096223	Extract string parts that are separated with commas	string msg = "13,G,true";\nvar myArray = msg.Split(",");\n\n// parse the elements\nint number;\nif (!Int32.TryParse(myArray[0], out number) throw new ArgumentException("Whrong input format for number");\nstring letter = myArray[1];\nstring b = myArry[2];\n\n// or also with a boolean instead\nbool b;\nif (!Int32.TryParse(myArray[2], out b) throw new ArgumentException("Whrong input format for boolean");	0
31990504	31984846	Get inner details of the TYPE of a method parameter using Roslyn	var methodNode = (MethodDeclarationSyntax)node;\nstring modelClassName = string.Empty;\n\nforeach (var param in methodNode.ParameterList.Parameters)\n{\n    var metaDataName = document.GetSemanticModelAsync().Result.GetDeclaredSymbol(param).ToDisplayString();\n//'document' is the current 'Microsoft.CodeAnalysis.Document' object\n    var members = document.Project.GetCompilationAsync().Result.GetTypeByMetadataName(metaDataName).GetMembers();\n    var props = (members.OfType<IPropertySymbol>());\n\n    //now 'props' contains the list of properties from my type, 'Type1'\n    foreach (var prop in props)\n    {\n        //some logic to do something on each proerty\n    }\n\n}	0
18678032	18677778	Generic Repository with nHibernate	public abstract class Repository<T, TId>\n{\n    public T Get(TId id)\n    {\n    }\n}	0
10532083	10528740	storing Multiple selected radiobutton's of gridview?	//  It will be on your submit button click \n    protected void getPinCode()\n    {\n        foreach (GridViewRow grdRows in gvSurvey.Rows)\n        {\n            RadioButton rbt1 = (RadioButton)grdRows.FindControl("rdbtn1");\n            RadioButton rbt2 = (RadioButton)grdRows.FindControl("rdbtn2");\n            RadioButton rbt3 = (RadioButton)grdRows.FindControl("rdbtn3");\n            RadioButton rbt4 = (RadioButton)grdRows.FindControl("rdbtn4");\n\n            string Value = RadioValue(rbt1);\n           //Similarly you can do for all radio button \n            if(!string.IsNullOrEmpty(Value))\n            {\n\n                lblMsg.Text = nominationsBiz.SaveSuggestion(ticketNo.ToString(), qtn_no, sqtn_no, Value);\n            }\n\n        }\n    }\n\n\n    protected string RadioValue(RadioButton Rbtlst)\n    {\n        string Value = "";\n\n        if (Rbtlst.Checked == true)\n        {\n            Value = Rbtlst.Text;\n        }\n        return Value;\n    }	0
3413398	3413375	Will indexing a SQL table improve the performance of a LINQ statement?	var results = from c in db.Customers\n    where c.LastName == 'Smith'\n    select c;	0
14655538	14655519	How to find first occurrence in c# list without going over entire list with LINQ?	strings.FirstOrDefault(s=>s.StartsWith("J"));	0
17077602	16588586	Cannot upload picture from hard drive to eBay sandbox with API	//Set the Picture Server URL for Sandbox \n            apiContext.EPSServerUrl = "https://api.sandbox.ebay.com/ws/api.dll";\n            //For production use this URL \n            //context.EPSServerUrl = "https://api.ebay.com/ws/api.dll"; \n\n\n            //Set file path of the picture on the local disk  \n            apiCall.PictureFileList = new StringCollection();\n\n            apiCall.PictureFileList.Add(@"C:\Users\Danny\Desktop\MyGalleryPicOnHardDrive.jpg");\n\n            //To specify a Gallery Image \n            item.PictureDetails = new PictureDetailsType();\n            //The first picture is used for Gallery URL \n            item.PictureDetails.GalleryType = GalleryTypeCodeType.Gallery;\n\n            //To add more pictures \n            //apiCall.PictureFileList.Add(@"C:\TEMP\pic2.gif");	0
20748141	20747737	TreeView NodeMouseClick - How to tell what part of node clicked	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {\n        var hit = treeView1.HitTest(e.Location);\n        if (hit.Location == TreeViewHitTestLocations.Label) {\n            // etc..\n        }\n    }	0
34002088	34001803	Fill List based on condition	List<float> optionList = specialBuildings\n    .AsParallel()\n    .Select(item => Vector2.Distance(item, house))\n    .ToList();	0
1202107	1202070	Best way to return a string from an HTTPHandler to a page that POSTs this .ashx file	public void ProcessRequest(System.Web.HttpContext context)\n{\n    context.Response.Write(mystring);\n}	0
15240098	15239442	Retrieving field data from a List of class objects	int index = Nodes1.FindIndex(var => var.nid == 1001);\n        double here4 = Nodes1[index].x;	0
24023564	24023529	Click Again action for LinkButton in asp.net	protected void LinkButton2_Click(object sender, EventArgs e)\n{\n    Panel2.Visible = !Panel2.Visible;\n}	0
11122761	11110772	Specifying parameters in the Using clause of an Oracle Merge statement	DECLARE\n  TYPE id_array_type IS TABLE OF NUMBER INDEX BY PLS_INTEGER;\n  TYPE options_array_type IS TABLE OF VARCHAR2 (100) INDEX BY PLS_INTEGER;\n\n  t_ids        id_array_type := :ids;\n  t_options    options_array_type  := :options;\n  v_state_id   NUMBER := :stateId;\nBEGIN\n  FORALL i IN 1 .. t_ids.count\n    EXECUTE IMMEDIATE '\n      MERGE INTO worker target\n      USING (SELECT :id id, :options options FROM dual) source\n      ON (source.id = target.id)\n      WHEN MATCHED THEN UPDATE SET target.stateId = :state_id, target.options = source.options'\n      USING t_ids (i), t_options (i), v_state_id;\nEND;	0
5112393	5112345	Calling methods with same signature dynamically	private Dictionary<string, Action<int>> doMethods = new Dictionary<string, Action<int>>();\npublic SomeClass()\n{\n    Type t = typeof(SomeClass);\n    var methods = t.GetMethods().Where(m => m.Name.StartsWith("Do"));\n\n    foreach(var method in methods)\n         doMethods.Add(method.Name, (Action<int>)Delegate.CreateDelegate(typeof(Action<int>), this, method, true));\n}\n\npublic void ActionFunction(string name, int num)\n{\n    this.doMethods[name](num);\n}	0
25119123	25117279	Find Height of Textblock / Text	textblock.Measure(new Size());\ntextblock.Arrange(new Rect());	0
6403623	6403602	Split parameter into string variables	string response = "access_token=129858573723395|2.AQB8yp6_GcD5hfxp.3600.1308506400.1-100000676383590|DUjbM8aN5PP-qzkLfTkGiZeCaLx4&expires=6099";\nstring token = response.Split('&')[0].Split('=')[1];\nConsole.WriteLine(token);\nConsole.ReadKey();	0
4758572	4757924	Post to Facebook user wall using Facebook.dll in WP7	var args = new Dictionary<string, object>();\n args["name"] = "Check this out";\n args["link"] = "www.xyz.com";\n args["caption"] = "";\n args["description"] = "description";\n args["picture"] = "";\n args["message"] = "Check this out";\n args["actions"] = "";\n\nFacebookAsyncCallback callBack = new FacebookAsyncCallback(this.postResult);\n fbApp.PostAsync("me/feed", args, callBack);  \n\n    private void postResult(FacebookAsyncResult asyncResult)\n    {\n        System.Diagnostics.Debug.WriteLine(asyncResult);\n    }	0
24815960	24815924	Displaying text box input to a label?	//Resets the placeholder text for password textbox\n    private void textBox2_Leave(object sender, EventArgs e)\n    {\n        if(!textBox2.Focused && textBox2.Text.Trim() == String.Empty)\n            textBox2.Text = "Password: ";\n    }\n\n//Resets the placeholder text for password textbox\n    private void textBox1_Leave(object sender, EventArgs e)\n    {\n        if(!textBox1.Focused && textBox1.Text.Trim() == String.Empty)\n            textBox1.Text = "Name: ";\n    }	0
28478624	28478471	How to get parent event inside ControlTemplate?	xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity"\nxmlns:ei="http://schemas.microsoft.com/expression/2010/interactions"  \n\n<i:Interaction.Triggers>\n    <ei:DataTrigger Binding="{Binding IsChecked,RelativeSource={RelativeSource AncestorType=RadioButton}}" Value=True>\n         <i:InvokeCommandAction Command="{Binding DataContext.OnTypeChangedCommand, RelativeSource={RelativeSource AncestorType={x:Type Window}}}" CommandParameter="{Binding Tag, RelativeSource={RelativeSource AncestorType=RadioButton}}}" />       \n    </ei:DataTrigger>\n</i:Interaction.Triggers>	0
16872681	16872650	Calculate Different Percentages Of Number In Textbox1 and display in textbox2 and 3	double number = int.Parse(textbox1.Text);\ndouble _95Percentage = number * 95 / 100;\ndouble _05Percentage = number - _95Percentage;\ntextbox2.Text = _95Percentage.ToString();\ntextbox3.Text = _05Percentage.ToString();	0
12768058	12767993	htmlagilitypack - parse a tag	System.Uri u = new System.Uri(url);\nstring LOC = System.Web.HttpUtility.ParseQueryString(u.Query).Get("LOC");	0
10592709	10567582	How can I get a Google Document's Description?	string description = document.DocumentEntry.Description;	0
24265027	22651372	C# LinkedResource using base64 string	var imageData = Convert.FromBase64String("/9j/4AAQSkZJRgABAgEASABIAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEB");\n\nvar contentId = Guid.NewGuid().ToString();\nvar linkedResource = new LinkedResource(new MemoryStream(imageData), "image/jpeg");\nlinkedResource.ContentId = contentId;\nlinkedResource.TransferEncoding = TransferEncoding.Base64;\n\nvar body = string.Format("<img src=\"cid:{0}\" />", contentId);\nvar htmlView = AlternateView.CreateAlternateViewFromString(body, null, "text/html");\nhtmlView.LinkedResources.Add(linkedResource);	0
19361419	19359521	How to get list of AD username from first name or surname (from one input textbox)	List<string> GetUserDetails()\n    {\n        List<string> allUsers = new List<string>();\n        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "myDomain",\n                                                "OU=ounit,dc=myDC,dc=com");\n\n        UserPrincipal qbeUser = new UserPrincipal(ctx);\n\n        qbeUser.GivenName = _UITxtUserName.Text;\n\n        PrincipalSearcher srch = new PrincipalSearcher(qbeUser);\n        foreach (var found in srch.FindAll())\n        {\n\n            allUsers.Add(found.DisplayName + "(" + found.SamAccountName + ")");\n        }\n        qbeUser = null; \n        qbeUser = new UserPrincipal(ctx);\n\n        qbeUser.Surname = _UITxtUserName.Text;\n\n        PrincipalSearcher srch1 = new PrincipalSearcher(qbeUser);\n        foreach (var found in srch1.FindAll())\n        {\n\n            allUsers.Add(found.DisplayName + "(" + found.SamAccountName + ")");\n        }\n\n        allUsers.Sort();\n\n        return allUsers;\n    }	0
5058839	5058827	Find all objects in List<T> with same property value	public class Card\n{\n    public int Rank { get; set; }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        var cards = new[] \n        {\n            new Card { Rank = 1 },\n            new Card { Rank = 2 },\n            new Card { Rank = 3 },\n            new Card { Rank = 2 },\n            new Card { Rank = 1 },\n        };\n\n        var groups = cards.GroupBy(x => x.Rank);\n        foreach (var group in groups)\n        {\n            Console.WriteLine("Cards with rank {0}", group.Key);\n            foreach (var card in group)\n            {\n                Console.WriteLine(card.Rank);\n            }\n        }\n    }\n}	0
3532707	3532680	I want to programatically generate a click on a DataGridView Row in C#	datagridviewRowClickedEventHandler(new object(), new eventargs());	0
4106159	4106145	Execute a bunch of commands in one fell swoop with ADO.NET	sqlCommand.CommandText = \n    @"DELETE FROM foo; \n      INSERT INTO foo (name) VALUES ('name1'); \n      INSERT INTO foo (name) VALUES ('name2');\n    ";	0
1432061	1432050	How to lock file	using (FileStream fs = \n         File.Open("MyFile.txt", FileMode.Open, FileAccess.Read, FileShare.None))\n{\n   // use fs\n}	0
27940113	27929015	Creating a Download link to a physical file on internal drive, within an MVC 4 Razor Application	byte[] fileBytes = System.IO.File.ReadAllBytes(System.IO.Path.Combine(DocumentsLocation, name + ".pdf"));\nstring fileName = name + ".pdf";\nreturn File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);	0
9984719	9984594	IQueryable<a> to ObservableCollection<a> where a = anonymous type	public ObservableCollection<T> ToObservableCollection<T>(IEnumerable<T> enumeration)\n{\n    return new ObservableCollection<T>(enumeration);\n}	0
2155540	2155508	user controls in asp.net prefixing string to child controls causing problem to refer them in javascript	someControl.ClientId	0
25132666	25132557	Getting Cell data from SQL to combobox	create PROCEDURE [dbo].[getcelldata]\n    @name varchar(50),@col varchar(5)\nAS\nBEGIN\ndeclare @sql varchar(100);\nset @sql  = 'SELECT [' + @col + '] from table where Name = '+ @name;    \nexec (@sql);\nEND	0
5292995	5292930	populating the combox and displaying the value in the combobox	BindingList<Member> comboBoxList = new BindingList<Member>();\nwhile (dbReader.Read())\n{\n    aMember = new Member\n                (dbReader["FirstName"].ToString(),\n                 dbReader["LastName"].ToString(),\n                 dbReader["StudentId"].ToString(),\n                 dbReader["PhoneNumber"].ToString());\n    // tb1.Text = dbReader["FirstName"].ToString();\n    // tb2.Text = dbReader["LastName"].ToString();\n    // tb1.Text = aMember.X().ToString();\n    //tb2.Text = aMember.Y(aMember.ID).ToString(); \n\n    comboList.Add(aMember)\n\n}\n\ncomboBox1.DataSource = comboBoxList; \n                        comboBox1.DisplayMember = "FirstName"; \n                        comboBox1.ValueMember = "ID";	0
375646	375590	How does one test a file to see if it's a valid XML file before loading it with XDocument.Load()?	try\n {\n   XDocument xd1 = new XDocument();\n   xd1 = XDocument.Load(myfile);\n }\n catch (XmlException exception)\n {\n     ShowMessage("Your XML was probably bad...");\n }	0
13829968	13828162	Facebook API, export group wall entries	/GROUP_ID/feed	0
12146462	12146433	Regex to retrieve includes from classic ASP	var includes = new List<string>();\nvar regex = new Regex("#include\\W+file=\"([^\"]+)\"");\nvar matchResult = regex.Match(fileContent);\nwhile (matchResult.Success) {\n    includes.Add(matchResult.Groups[1].Value);\n    matchResult = matchResult.NextMatch();\n}	0
1675892	1675102	WPF :: Copying an image to folder in application directory	var assemblyLocation = Assembly.GetExecutingAssembly().Location;\nvar applicationDirectory = Path.GetDirectoryName(assemblyLocation);\nvar imagesDirectory = Path.Combine(applicationDirectory, "Images");	0
1467981	1454440	Select Range of Text in WPF RichTextBox (FlowDocument) Programmatically	Public Function GoToPoint(ByVal start As TextPointer, ByVal x As Integer) As TextPointer\n    Dim out As TextPointer = start\n    Dim i As Integer = 0\n    Do While i < x\n        If out.GetPointerContext(LogicalDirection.Backward) = TextPointerContext.Text Or _\n             out.GetPointerContext(LogicalDirection.Backward) = TextPointerContext.None Then\n            i += 1\n        End If\n        If out.GetPositionAtOffset(1, LogicalDirection.Forward) Is Nothing Then\n            Return out\n        Else\n            out = out.GetPositionAtOffset(1, LogicalDirection.Forward)\n        End If\n\n\n    Loop\n    Return out\nEnd Function	0
11324866	11324688	How to refresh datagrid in WPF	myGrid.ItemsSource = null;\nmyGrid.ItemsSource = myDataSource;	0
18673000	18672429	How to show the SelectedItem of the ListPicker?	private void categoriesListPicker_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    if (categoriesListPicker.SelectedItem != null)\n    {\n                string selectedItem = categoriesListPicker.SelectedItem as string;\n                MessageBox.Show(selectedItem);\n    }\n}	0
11912428	11912412	single quotes escape during string insertion into a database	string sql= "insert into gtable (1text, 1memo) " + \n            "values ('" + textBox3.Text.Replace("'", "''") + "', null)";	0
923754	923740	transactional sqlite? in C#	using (DbTransaction dbTrans = myDBConnection.BeginTransaction())\n{\n     using (DbCommand cmd = myDBConnection.CreateCommand())\n     {\n         ...\n     }\n     dbTrans.Commit();\n}	0
14979896	14979868	Call overload method with default parameters	foo(1,2,d:true); //will call the second method.	0
3264199	3264131	Is it possible to read serial number from a harddisk in c#?	using System;\nusing System.Management;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            ManagementClass mangnmt = new ManagementClass("Win32_LogicalDisk");\n            ManagementObjectCollection mcol = mangnmt.GetInstances();\n            string result = "";\n            foreach (ManagementObject strt in mcol)\n            {\n                result += "Name              : " + Convert.ToString(strt["Name"]) + Environment.NewLine;\n                result += "VolumeName        : " + Convert.ToString(strt["VolumeName"]) + Environment.NewLine;\n                result += "VolumeSerialNumber: " + Convert.ToString(strt["VolumeSerialNumber"]) + Environment.NewLine;\n                result += Environment.NewLine;\n            }\n            Console.Out.WriteLine(result);\n            Console.In.ReadLine();\n        }\n    }\n}	0
750857	750778	ASP.NET Get Original Text of Label	textLabel.Attributes.Add("data", textLabel.Text);	0
1632126	1631926	Find which account a service is set to "Log On As"	string serviceName = "aspnet_state";\n\nSelectQuery query = new System.Management.SelectQuery(string.Format(\n    "select name, startname from Win32_Service where name = '{0}'", serviceName));\nusing (ManagementObjectSearcher searcher =\n    new System.Management.ManagementObjectSearcher(query))\n{\n    foreach (ManagementObject service in searcher.Get())\n    {\n        Console.WriteLine(string.Format(\n            "Name: {0} - Logon : {1} ", service["Name"], service["startname"]));\n    }\n}	0
33700472	33700164	How can I disable Windows Firewall?	Type netFwPolicy2Type = Type.GetTypeFromProgID("HNetCfg.FwPolicy2");\nINetFwPolicy2 mgr = (INetFwPolicy2)Activator.CreateInstance(netFwPolicy2Type);\n\n// Gets the current firewall profile (domain, public, private, etc.)\nNET_FW_PROFILE_TYPE2_ fwCurrentProfileTypes = (NET_FW_PROFILE_TYPE2_)mgr.CurrentProfileTypes;\n\n// Get current status\nbool firewallEnabled = mgr.get_FirewallEnabled(fwCurrentProfileTypes);\nstring frw_status = "Windows Firewall is " + (firewallEnabled ?\n"enabled" : "disabled");\n\n// Disables Firewall\nmgr.set_FirewallEnabled(fwCurrentProfileTypes, false);	0
25378639	25378598	Rounding Off decimal to two places	Cost.ToString("0.00")	0
29219340	29219276	folderbrowserdialog selectedpath returns no value	if (folderfinder.ShowDialog() == DialogResult.OK)\n{\n    Console.Write(folderfinder.SelectedPath);\n}	0
12923339	12923194	Use data from database to populate RadioButtonList	var optionList = new List<ListItem>();\n\nfor (var i = 0; i < 4; i++)\n{\n  var newItem = new ListItem()\n  {\n      Value = count.ToString(),\n      Text = string.Format("Option {1}", count.ToString());\n  };\n\n  optionList.Add(newItem);\n}\n\nAnswers.DataSource = optionList;\nAnswers.DataBind();	0
9534910	9534718	Put SqlDataReader data into a DataTable while i process it	SqlDataReader reader = com.ExecuteReader();\nDataTable dt = new DataTable();\ndt.Load(reader);	0
6058217	6058196	How to overcome from the error	ds.Tables[0].Rows.Count	0
3682716	3682635	Take Screenshots of WebBrowser Control	private void copyToolStripMenuItem_Click(object sender, EventArgs e) {\n    int width, height;\n    width   = webBrowser1.ClientRectangle.Width;\n    height  = webBrowser1.ClientRectangle.Height;\n    using (Bitmap image = new Bitmap(width, height)) {\n        using (Graphics graphics = Graphics.FromImage(image)) {\n            Point p, upperLeftSource, upperLeftDestination;\n            p                       = new Point(0, 0);\n            upperLeftSource         = webBrowser1.PointToScreen(p);\n            upperLeftDestination    = new Point(0, 0);\n            Size blockRegionSize = webBrowser1.ClientRectangle.Size;\n            graphics.CopyFromScreen(upperLeftSource, upperLeftDestination, blockRegionSize);\n        }\n        image.Save("C:\\Test.bmp");\n    }\n}	0
32566981	32566485	SQL Server incrementing a column's value depending on a trigger from another table	CREATE VIEW StoreWithStatistics AS\n  SELECT s.*, \n         COUNT(r.StoreRating) OVER (PARTITION BY s.StoreID) AS Number_of_Ratings_Recieved,  \n         AVG(r.Rating_for_Store_out_of_Ten) OVER (PARTITION BY s.StoreID) AS Average_Rating\n  FROM STORE s\n  LEFT JOIN Rating r on s.StoreID = r.StoreID	0
13858771	13857410	Limit rewritten URL length in URL Rewriter	RewriteBase /\nRewriteCond %{REQUEST_FILENAME} !-f\nRewriteCond %{REQUEST_FILENAME} !-d\nRewriteRule ^.{100} /Default.aspx [R=301,L]	0
4463692	4463505	How to sort DataGridView when bound to a binding source that is linked to an EF4 Entity	private void myDataGridView_ColumnHeaderMouseClick(object sender, DataGridViewCellMouseEventArgs e)\n  {\n     DataGridViewColumn column = myDataGridView.Columns[e.ColumnIndex];\n\n     _isSortAscending = (_sortColumn == null || _isSortAscending == false);\n\n     string direction = _isSortAscending ? "ASC" : "DESC";\n\n     myBindingSource.DataSource = _context.MyEntities.OrderBy(\n        string.Format("it.{0} {1}", column.DataPropertyName, direction)).ToList();\n\n     if (_sortColumn != null) _sortColumn.HeaderCell.SortGlyphDirection = SortOrder.None;\n     column.HeaderCell.SortGlyphDirection = _isSortAscending ? SortOrder.Ascending : SortOrder.Descending;\n     _sortColumn = column;\n  }	0
7371824	7371652	Custom Helper  in Asp.net mvc3	public static class HelperExtensions\n{\n    public static MvcHtmlString Menu(this HtmlHelper html, Action<IList<ToolbarAction>> addActions)\n    {\n        var menuActions = new List<ToolbarAction>();\n        addActions(menuActions);\n\n        var htmlOutput = new StringBuilder();\n\n        htmlOutput.AppendLine("<div id='menu'>");\n\n        foreach (var action in menuActions)\n            htmlOutput.AppendLine(html.ActionLink(action.Text, action.Action, action.Controller, new { @class = action.Name }).ToString());\n\n        htmlOutput.AppendLine("</div>");\n\n        return new MvcHtmlString(htmlOutput.ToString());\n    }\n}	0
21628713	21620506	How to get Word.Range.Start/End of each Paragraph in Header in VSTO	foreach (Word.Section section in document.Sections)\n{\n    foreach (Word.HeaderFooter wordFooter in section.Headers)\n    {\n        foreach (Word.Paragraph para in wordFooter.Range.Paragraphs) // see the change of wordFooter in this line\n        {\n            Word.Range range = para.Range;\n\n            range.SetRange(1, 5);\n            range.Delete();\n        }\n    }\n}	0
11787690	11787663	Remove specific words from a string (case insensitive)	(?i)(associate DEGREE in ELECtronics)	0
2681045	2680664	How to insert selected rows value of Gridview into Database in .net	for (int i = 0; i < grdList.Rows.Count; i++)\n    {\n        string key = grdList.DataKeys[i].Value.ToString();\n        if (((CheckBox)grdList.Rows[i].FindControl("chkSelect")).Checked)\n            foreach (TargetObject obj in objects)\n                if (obj.Key == key)\n                {\n                    //do something like below\n                    flag = true;\n                    break;\n                }\n    }	0
11123843	11123069	Sorting the objects of a DataTable collection	DataView view = tables.DefaultView;\n\nview.Sort = "Name";\n\nforeach (DataRowView row in view)\n{\n}	0
33615848	33610161	Windows universal app and hot keys	// Listen to the window directly so focus isn't required\n                Window.Current.CoreWindow.Dispatcher.AcceleratorKeyActivated +=\n                    CoreDispatcher_AcceleratorKeyActivated;\n                Window.Current.CoreWindow.PointerPressed +=\n                    this.CoreWindow_PointerPressed;	0
7466646	7466628	Is there a way to get the Remote IP Endpoint from a TcpClient like you can in a Socket?	myClient.Client.RemoteEndPoint	0
14625564	14617714	How to stub a method conditionally with VS Fakes?	var stub = new StubIObject\n{\n    Foo = (value) => \n       {\n           if (value == 100)  \n              // This covers the case (It.Is<int>(t => t == 100))\n              return value * 1.10;\n           return value;    // This covers the default case (It.IsAny<T>)\n        }\n};	0
1406812	1406795	C# call a static method at runtime without a build time reference?	Type t = Type.GetType(className);\n\n// get the method\nMethodInfo method = t.GetMethod("MyStaticMethod",BindingFlags.Public|BindingFlags.Static);\n\nThen you call the method:\n\nmethod.Invoke(null,null); // assuming it doesn't take parameters	0
1403464	1403443	How to Enumerate a generic List<T> without know the type	void Enumerate<T>(List<T> items)\n{\n  for(var item in items) \n  {\n    //...\n  }\n}	0
29278763	29278728	Removing characters from a string with lengths greater than 2	var s = "2109389";\nvar sub = s.SubString(0,2);	0
14221855	14221728	Sorting Listbox Items by DateTime values	ArrayList arList = new ArrayList(); \nforeach (object obj in listBox1.Items)\n{\n    arList.Add(obj);\n} \narList.Sort(); \nlistBox2.Items.Clear();\nforeach(object obj in arList)\n{\n    listBox2.Items.Add(obj); \n}	0
11790931	11775095	Wrong xml schema from datatable	DataRow row = ResultDT.NewRow();\nfor (int i = 0; i < ValToAppendDt.Count; i++)\n    {            \n        row[i] = ValToAppendDt[i].ToString();            \n    }\nResultDT.Rows.Add(row);	0
11748231	11747368	Set Command Timeout in entity framework 4.3	((IObjectContextAdapter)context).ObjectContext.CommandTimeout = 180;	0
19981520	19981461	How to check containsKey in Dictionary<string, Dictionary<string, Dictionary<string, string>>>	Dictionary<string, Dictionary<string, Dictionary<string, string>>> dict= new Dictionary<string, Dictionary<string, Dictionary<string, string>>>(); \n if (dict.ContainsKey(outerKey))\n {\n   var innerDict = dict[outerKey];\n   if (innerDict.ContainsKey(innerKey))\n   {  \n       var innerMost = innerDict[innerKey];\n       if (innerMost.ContainsKey(innerMostKey))\n        var item = innerMost[innerMostKey]; // This is the item of inner most dict\n    }\n }	0
31395389	31395293	How to find intersection between collections	var item = from c in containers\n           from o in c.Objects\n           group c.ContainerName by o into g\n           where g.Distinct().Count() > 1\n           select g.Key;	0
24169867	24169721	String was not recognised as a valid datetime	DateTime yeer;\n\nif (!string.IsNullOrEmpty(txtBookDate.Text))\n    yeer = Convert.ToDateTime(txtBookDate.Text);\nelse\n    yeer = new DateTime(9999, 12, 31);	0
13391772	13391477	Receiving MouseMove events from parent control	Point mousePoint;\n\nprivate void panel1_MouseMove(object sender, MouseEventArgs e)\n{\n    mousePoint = e.Location;\n}\n\nprivate void button1_MouseMove(object sender, MouseEventArgs e)\n{\n    mousePoint = new Point(button1.Location.X + e.Location.X, button1.Location.Y + e.Location.Y);\n}	0
779235	779193	Linq to Entities (EF): How to get the value of a FK without doing the join	Employee employee = context.Employees.Single(e => e.employeeID == 1);\n\nInt32 vendorID = (Int32)employee.tbl_vendorsReference.EntityKey.\n   EntityKeyValues[0].Value;	0
13250426	13249324	crystal report with subreport not diplaying data in subreport	SalesProductReport rptDoc = new SalesProductReport(); //Main report\n\n    DataTable dt1, dt2;\n    dt1 = new SalesMasterRepository().GetSalesHeaderData(Salesid);\n\n     dt2 = new SalesMasterRepository().GetSalesFooterData(Salesid);\n\n     DataTable dtproductview=getProductViewDetails();\n    salesrpt.Subreports["Sales_header1.rpt"].SetDataSource(dt1);//datasource for subreport\n\n        rptDoc .SetDataSource(dtproductview);//Mainreport datasourcce\n       rptDoc .Subreports["SalesFooter.rpt"].SetDataSource(dt2);//datasource for subreport\n\n    CrystalReportViewer1.ReportSource = rptDoc ;	0
32544316	32544267	Single producer multiple consumer implementation	Consumer consumer = consumers.Take();\nvar result = consumer.Read(data); //do stuff with result \nif (consumers.TryAdd(consumer)) \n{ \n   //ok \n}	0
10753006	10751244	The Monodroid-equivalent to searchable in Android	[IntentFilter (new[]{Intent.ActionSearch})]\n[MetaData ("android.app.searchable", Resource="@xml/searchable")]	0
204393	204037	TcpClient field of abstract base class constantly being disposed	if (this.tcpClient == null)\n  {\n    this.tcpClient = new TcpClient();\n  }\n\n  try\n  {\n    if (!this.tcpClient.Connected)\n    {\n      this.tcpClient.Connect(EthernetAddress, TcpPort);\n    }\n  }\n  catch(Exception ex)\n  {\n    throw new TimeoutException("The device did not respond.\n" + ex.Message);\n  }	0
20684925	20643641	Reliable method for detecting if Webex Client is running	atmgr.exe	0
9067731	9067662	Change data in an IQueryable object	var results = from p in db.Persons \n              join c in db.CitysInfo on p.cityID equals c.cityId\n              select new \n              {\n                name = p.name,\n                family = p.family,\n                CityName = c.CityName,\n              }	0
20897873	20897823	How to show print dialogue when i press control + P in windows form	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        if (keyData == (Keys.Control | Keys.P)) {\n            printDialog1.ShowDialog(this);\n            return true;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }	0
29829952	29343103	Utc Date saving as Local date in Sqlite	internal const string DateTimeFormat = "yyyy-MM-dd HH:mm:ss";\ncmd.Parameters.Add("@Threshold", DbType.DateTime).Value = threshold.ToString(DateTimeFormat);	0
26796256	26796066	print the string by removing the PRIME ASCII CHARACTERS	M  78\ne  101  -> Is prime number\nh  104\nt  116\na  97   -> Is prime number	0
6766118	6766098	Iterating a List in an Object Initializer	PartnershipIDs = p.Partnerships.Select(par => par.ID).ToList()	0
2894977	2894953	how to split the word and get the 4 letter prefix in C#	String userName = "LICTowner";\nString prefix = userName.Substring(0,4); // LICT\nString restOfWord = userName.Substring(4); // owner	0
2934989	2934936	Best way to reverse string in c#	String.Join(" ? ", "Products ? X1 ? X3".Split(new[]{" ? "}, \n    StringSplitOptions.None).Reverse().ToArray());	0
12305514	12277049	settings search like Google Chrome for WPF	var settings = new ObservableCollection<SettingsClassType>();\nSettingsCollView = CollectionViewSource.GetDefaultView(settings);\nSettingsCollView.Filter += (o) => {\n  var setting = (SettingsClassType)o;\n  return string.IsNullOrEmpty(YourSearchInput)\n         || setting.Name.Contains(YourSearchInput);\n}\n\nprivate string yourSearchInput;\npublic bool YourSearchInput\n{\n  get { return yourSearchInput; }\n  set\n  {\n    if (value == yourSearchInput) {\n      return;\n    }\n    yourSearchInput= value;\n    // filer your collection here\n    SettingsCollView.Refresh();\n    this.NotifyPropertyChanged("YourSearchInput");\n  }\n}	0
10987599	10987536	Can I use List of objects as Dictionary Keys ?	List<int> a = new List<int>(1, 2, 3);\nList<int> b = new List<int>(1, 2, 3); //different instance than a\n\nDictionary<List<int>, int>> map = new Dictionary<List<int>, int>>();\nmap.Add(a, a.Sum());\nint aSum = map[b]; //KeyNotFoundException because this is a different instance.\n\n\nHashSet<int> a = new HashSet<int>(1, 2, 3);\nHashSet<int> b = new HashSet<int>(1, 2, 3); //different instance than a\n\nDictionary<HashSet<int>, int>> map1 = new Dictionary<HashSet<int>, int>>();\nmap1.Add(a, a.Sum());\nint aSum = map1[b]; //KeyNotFoundException because this is a different instance.\n\n\nHashSet<int> a = new HashSet<int>(1, 2, 3);\nHashSet<int> b = new HashSet<int>(1, 2, 3); //different instance than a\n\nDictionary<HashSet<int>, int>> map2 = new Dictionary<HashSet<int>, int>>\n  (HashSet<int>.CreateSetComparer()); //instance comparison not used - equal sets are equal\nmap2.Add(a, a.Sum());\nint aSum = map2[b]; //6	0
18985640	18985525	Assigning a Readonly Field via Virtual Member in Abstract Class's Constructor	public abstract class FooBase\n{\n    private readonly IDictionary<string,object> _readonlyCache;\n\n    protected FooBase(IDictionary<string,object> cache)\n    {\n        _readonlyCache = cache;\n    }\n}	0
3830253	3830228	Is there a MessageBox equivalent in WPF?	System.Windows.MessageBox	0
34288826	34288574	AutoMapper set destination to null on condition of source property	class Converter : TypeConverter<Foo, Bar>\n{\n    protected override Bar ConvertCore(Foo source)\n    {\n        if (source.Code != 0)\n            return null;\n        return new Bar();\n    }\n}\n\n\nstatic void Main(string[] args)\n    {\n        Mapper.CreateMap<Foo, Bar>()\n            .ConvertUsing<Converter>();\n\n\n        var bar = Mapper.Map<Bar>(new Foo\n        {\n            Code = 1\n        });\n        //bar == null true\n    }	0
3442967	3442921	Close form without exit application	this.Hide();\nForm2 form2 = new Form2();\nform2.Show();	0
22881792	22881407	Retrieve Value Partial View and Pass to Controller	[HttpPost]\npublic ActionResult Index(int CustomerId)\n{\n   //process\n   Return View("Load")\n\n}	0
21335443	21334902	Unable to remove folder permissions (access rules) using DirectorySecurity facilities	DirectorySecurity objSecObj = directory.GetAccessControl();\nAuthorizationRuleCollection acl = objSecObj.GetAccessRules(true, true,\n                                            typeof(System.Security.Principal.NTAccount));\nobjSecObj.SetAccessRuleProtection(true, false); //to remove inherited permissions\nforeach (FileSystemAccessRule ace in acl) //to remove any other permission\n{    \n    objSecObj.PurgeAccessRules(ace.IdentityReference);  //same as use objSecObj.RemoveAccessRuleSpecific(ace);\n}\n\ndirectory.SetAccessControl(objSecObj);	0
3565861	3565564	Find all optional parameters and remove them	foreach (Type tp in currentAssembly.GetTypes())\n    foreach (MethodInfo func in tp.GetMethods())\n        if(func.GetParameters().Any(p=>p.IsOptional))\n            Console.WriteLine(func.ToString());	0
17080563	17080431	Recursive sum to find single digit	int a = 123456;\nint result = a;\n\nwhile (result >= 10)\n   result = result.ToString()\n                  .Sum(x => int.Parse(x.ToString()));	0
1657262	1657258	Quickest way to determine if a 2D array contains an element?	private class DataContainer\n{\n    private readonly int[,] _data;\n    private HashSet<int> _index;\n\n    public DataContainer(int[,] data)\n    {\n        _data = data;\n    }\n\n    public bool Contains(int value)\n    {\n\n        if (_index == null)\n        {\n            _index = new HashSet<int>();\n            for (int i = 0; i < _data.GetLength(0); i++)\n            {\n                for (int j = 0; j < _data.GetLength(1); j++)\n                {\n                    _index.Add(_data[i, j]);\n                }\n            }\n        }\n        return _index.Contains(value);\n    }\n}	0
2900186	2861779	XmlSerializer: The string '' is not a valid AllXsd value	[XmlElement("Valid")]\n    public string _Valid\n    {\n        get;\n        set;\n    }\n\n    [XmlIgnore]\n    public bool? Valid\n    {\n        get\n        {\n            if (!string.IsNullOrWhiteSpace(_Valid))\n            {\n                return bool.Parse(_Valid);\n            }\n\n            return null;\n        }\n    }	0
6151495	6149793	User driven session expiration	Session.TimeOut= [=nMinutes]	0
7151295	7151067	c# minimum of two numbers if one or both is greater than 0	private int GetSmallestNonNegative(int a , int b)\n{\n    if (a >= 0 && b >= 0)\n        return Math.Min(a,b);\n    else if (a >= 0 && b < 0)\n        return a;\n    else if (a < 0 && b >= 0)\n        return b;\n    else\n        return 0;\n}	0
16516936	16516883	stored Procedure usage in ASP.NET	System.Data.CommandType.StoredProcedure	0
27012070	27012027	Weird Result of String	string str = @"//\n// Use a new char[] array of two characters (\r and \n) to break\n// lines from into separate strings."+ @" \n" + @" Use RemoveEmptyEntries\n// to make sure no empty strings get put in the string array. \n//";	0
15568013	15567648	Renaming a public class in a shipped library	[Obsolete("Please use LatestGreatest instead.")]\npublic class OldSchool\n{\n    private LatestGreatest _Target;\n\n    public OldSchool()\n    {\n        _Target = new LatestGreatest();\n    }\n\n    public void DoSomething()\n    {\n        _Target.DoSomething();\n    }\n\n    [Obsolete("Please use LatestGreatest.DoItInSomeOtherWay()")]\n    public void DoTheOldWay()\n    {\n        _Target.DoItInSomeOtherWay();\n    }\n}\n\npublic class LatestGreatest\n{\n    public void DoSomething()\n    {\n        Console.WriteLine("I'm so fresh and cool.");\n    }\n\n    public void DoItInSomeOtherWay()\n    {\n        Console.WriteLine("Let's do it...");\n    }\n}	0
5529564	5529539	C# Round Color to Colors in a list	string closestColor = "";\ndouble diff = 200000; // > 255?x3\n\nforeach(string colorHex in validColors)\n{\n    Color color = System.Drawing.ColorTranslator.FromHtml("#"+colorHex);\n    if(diff > (diff = (c.R - color.R)?+(c.G - color.G)?+(c.B - color.B)?))\n        closestColor = colorHex;\n}\n\nreturn closestColor;	0
33284929	33273230	How to add radio buttons dynamically and display them in a button click in map control(windows phone 8.1)	MapControl.SetLocation(st, new Geopoint(/* Your location info */));\nMyMap.Children.Add(st);	0
9428834	9428734	How to find the file by its partial name?	static void Main(string[] args)\n    {\n        string partialName = "171_s";\n\n        DirectoryInfo hdDirectoryInWhichToSearch = new DirectoryInfo(@"c:\");\n        FileInfo[] filesInDir = hdDirectoryInWhichToSearch.GetFiles("*" + partialName + "*.*");\n\n        foreach (FileInfo foundFile in filesInDir)\n        {\n            string fullName = foundFile.FullName;\n            Console.WriteLine(fullName);\n        }\n\n    }	0
274025	274022	How do I pronounce "=>" as used in lambda expressions in .Net	x => x * 2;	0
6078736	6078718	Return a generic IList filtered by a Where or Select extension method	return myItems.Where(i => i.Name == name).ToList();	0
24454483	24433102	Reading a text file with a specific structure	using System;\nusing System.Linq;\nusing System.Reflection;\n\npublic class Program\n{\n    public static void Main()\n    {\n        String input = "\"thing 1\" \"thing 2\" \"thing 3\" \"thing 4\"";\n        var result = input.Split(new char[]{'\"'}).Where(p=> !String.IsNullOrWhiteSpace(p));\n        foreach(string v in result)\n            Console.WriteLine(v);\n    }\n}	0
9299278	9299052	Locking in a factory method	// Assuming the allLocks class member is defined as follows:\nprivate static AutoResetEvent[] allLocks = new AutoResetEvent[10];\n\n\n// And initialized thus (in a static constructor):\nfor (int i = 0; i < 10; i++) {\n    allLocks[i] = new AutoResetEvent(true);\n}\n\n\n// Your method becomes\nvar lockIndex = id % allLocks.Length;\nvar lockToUse = allLocks[lockIndex];\n\n// Wait for the lock to become free\nlockToUse.WaitOne();\ntry {\n    // At this point we have taken the lock\n\n    // Do the work\n} finally {\n    lockToUse.Set();\n}	0
14084957	14084860	Open Web Browser from XAML app	await Launcher.LaunchUriAsync(new Uri(uri));	0
8041998	8041620	How do I use CollectionViewSource to sort xml records by date?	public class DateStringComparer : IComparer\n{\n    public int Compare(object x, object y)\n    {\n        return DateTime.Compare(DateTime.Parse(x.ToString()), DateTime.Parse(y.ToString()));\n    }\n}	0
20857930	20798542	Validate textbox in c# with wpf	this.DataContext = workAssignement;	0
3834574	3834544	Loop through controls of a UserControl	foreach (var ctl in this.Controls)\n{\n    if (ctl is RadioButton)\n    {\n       // stuff\n    }\n}	0
17974184	17973981	HttpClient PostAsync Invalid Post Format	var values = new List<KeyValuePair<string, string>>();\n\nvalues.Add(new KeyValuePair<string, string>("Item1", "Value1"));\nvalues.Add(new KeyValuePair<string, string>("Item2", "Value2"));\nvalues.Add(new KeyValuePair<string, string>("Item3", "Value3"));\n\nusing (var content = new FormUrlEncodedContent(values))\n{\n    client.PostAsync(postUri, content).Result)\n}	0
2676118	2675958	testing for one item in dictionary<k,v>	public static T GetFirstElementOrDefault<T>(IEnumerable<T> values)\n{\n  T value = default(T);\n  foreach(T val in values)\n  {\n    value = val;\n    break;\n  }\n  return value;\n}	0
6504334	6504199	C# problem in append items to XML document	xmlDoc.Root.Add(\n    new XElement("product",\n        new XElement("name", "456"),\n        new XElement("price", "456")));	0
15126664	15126594	Get relative path for a file asp.net	Server.MapPath("_File1.txt");	0
33888604	33888084	How to get all ip address in LAN?	Dns.GetHostAddresses	0
15071876	15071824	How to call base constructor inside constructor depending on some parameter?	public SomeConstructor() \n  : base(Configuration.ConnectionString) {\n\n}\n\npublic static Configuration {\n  public static string ConnectionString {\n    get { \n      /* some logic to determine the appropriate value */\n#if DEBUG\n      return ConfigurationManager.ConnectionStrings["DebugConnectionString"]; \n#else\n      return ConfigurationManager.ConnectionStrings["ReleaseConnectionString"]; \n#endif\n    } \n  }\n}	0
22636126	22635607	Are there rendering issues when storing a sizeable amount of text in a Rich Text Box using WPF?	List<String> Lines = new List<String>();\nSystem.IO.StreamReader file = \n   new System.IO.StreamReader("c:\\test.txt");\nwhile((line = file.ReadLine()) != null)\n{\n   myFlowDoc.Blocks.Add(new Paragraph(new Run(x)));\n   Lines.Add(line);\n}\n\nfile.Close();	0
14339331	14339046	Custom Routing with ASP.NET Web API	config.Routes.MapHttpRoute("MyRoute", "Region/{regionId}/Countries", new { controller = "Region", action = "GetCountries" });	0
26198765	26195275	How to get first item from XmlSchema.Elements	var v = yourObject.Elements.Names.OfType<XmlQualifiedName>().FirstOrDefault();\nvar w = yourObject.Elements.Values.OfType<XmlSchemaElement>().FirstOrDefault();	0
11636851	11636812	How can I truncate a string at the first instance of a character?	text.Substring(0, text.IndexOf('_'));	0
20126698	6988991	Getting store item description	&IncludeSelector=Details,Description,TextDescription	0
30343065	30307366	ServiceStack V4 Basic Auth with wrong credentials + CORS	UncaughtExceptionHandlers.Add((req, res, name, exception) =>\n{\n     //this is needed for inclusion of CORS headers in http error responses\n     //(for example when invalid user credentials passed)\n     res.ApplyGlobalResponseHeaders();\n});	0
31065568	31064796	How to make next page visible false?	else if(PageNumber < vcnt)\n{\n    //linkNext.Visible = true;\n    // Change it to\n\n    linkNext.Visible = !pagedData.IsLastPage;\n    linkPrevious.Visible = !pagedData.IsFirstPage;\n}	0
23607731	23607446	Create a blob storage container programmatically	public void AddCompanyStorage(string subDomain)\n        {\n            //get the storage account.\n            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(\n                System.Configuration.ConfigurationManager.AppSettings["StorageConnectionString"].ToString());\n\n            //blob client now\n            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();            \n\n            //the container for this is companystyles\n           CloudBlobContainer container = blobClient.GetContainerReference(subDomain);\n\n            //Create a new container, if it does not exist\n           container.CreateIfNotExist();\n        }	0
23691990	23690618	How to use IDisposable pattern on Windows Form	protected override void OnClosed(EventArgs e)\n{\n    base.OnClosed(e);\n\n    if (ds != null)\n        ds.Dispose();\n}	0
22888394	22886528	Unable To Connect using Server Explorer	MYSERVER\SQLEXPRESS	0
6309763	6309668	Take n most records with aggregate	this.ObjectContext.Logs\n        .Where(w => w.Message == "Created User" || \n               w.Message == "Removed User" || \n               w.Message == "Updated User")\n        .GroupBy(w => w.Username)\n        .OrderByDescending(g => g.Count())\n        .Select(g => g.Key)\n        .Take(5);	0
5567760	5565792	Schedule a windows service to run every two hours	private ManualResetEvent resetEvent = new ManualResetEvent(false);\nprivate RegisteredWaitHandle handle;\n\npublic void OnStart()\n{\n    resetEvent.Reset();\n    handle = ThreadPool.RegisterWaitForSingleObject(resetEvent, callBack, null, 7200000, false);\n}\n\npublic void OnStop()\n{\n    reset.Set();\n}\n\nprivate void callBack(object state, bool timeout)\n{\n    if (timeout)\n    {\n        //Do Stuff Here\n    }\n    else\n    {\n        handle.Unregister(null);\n    }   \n}	0
2274899	2274885	Rounding to unit above with C#	Math.Ceiling	0
29017808	29017716	Argument in Event Handler using Lambda	pd.PrintPage += (s, eventArgs) =>\n{\n    Image i = Image.FromFile(newFile);\n    Point p = new Point(0, 0);\n    eventArgs.Graphics.DrawImage(i, p);\n};  // <-- here	0
7756184	5771058	How to use contentmenustrip for listview and listviewitem? C#	if(e.Buttons == MouseButton.Right)\n          contextMenuStrip1.Show(e.X+val1, e.Y+val2);	0
22236222	22236038	is it possible to select a string in linq to entity framework?	var cars = brokenCars.Where(c => c.status == 3)\n                     .Select(c => new { status = "broken", c.name, c.type });	0
24172590	24169145	Deserializing JSON List object	return Request.CreateResponse(HttpStatusCode.OK, Active);	0
20283976	20267107	How to add a Image into a GridView in Visual Web Part from Sharepoint	DataTable table;\nImage blueStar = new Image();\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n\n   blueStar = ImageBlueStar;\n\n   table= new DataTable();\n\n   table.Columns.Add("Title Text");\n\n   tabela.Rows.Add("URL FROM IMAGE", "SOME TEXT");\n\n   SPGridView novaGrid = new SPGridView();\n   novaGrid.DataSource = table.DefaultView;\n   novaGrid.AutoGenerateColumns = false;\n   novaGrid.Columns.Add(new ImageField { DataImageUrlField = "Title Text"});\n\n\n   Controls.Add(novaGrid);\n   novaGrid.DataBind();\n\n}	0
22166208	21798341	mixing wavestream with NAudio	r1 = new WaveFileReader(...);\nr2 = new WaveFileReader(...);\nr1.Read(arr1, 0, arr1.Length);    \nr2.Read(arr2, 0, arr2.Length);\nshort[] firstPCM16 = ALawDecoder.ALawDecode(arr1);\nshort[] secondPCM16 = ALawDecoder.ALawDecode(arr2);\nbyte[] result1 = new byte[firstPCM16.Length * sizeof(short)];\nbyte[] result1 = new byte[secondPCM16.Length * sizeof(short)];\nBuffer.BlockCopy(firstPCM16, 0, result1, 0, result1.Length);\nBuffer.BlockCopy(secondPCM16, 0, result2, 0, result2.Length);\nfor (...)\n{                        \n    mixed[i] = (byte)(result1[i] + result2[i]);//No need to dividing by 2 because r1  and r2 are 8 bit ALaw and return value of ALawDecoder is 16 bit pcm\n}	0
2924085	2924011	How to calculate unbound column value based on value of bound colum in DatagGridView?	//untested\nprivate void dgvItems_CellValueNeeded(object sender, DataGridViewCellValueEventArgs e)\n{\n  if (e.Column == 0)\n  {\n     e.Value = dgvItems.CurrentRow.Cells[2].Value * 5; //simplified example\n  }\n}	0
7165761	7150770	ShowDialog without Blocking Caller	myForm.BeginInvoke(new Action(() => new LoadingForm().ShowDialog()));	0
28305269	28285055	How to add client certificate in ASP.NET Web API in-memory testing?	var server = new HttpServer(configuration);\n        var invoker = new HttpMessageInvoker(server);\n        var certificate = GetCertificate();\n\n        var request = new HttpRequestMessage(HttpMethod.Get, "http://localhost/YourPath");\n        request.Properties[HttpPropertyKeys.ClientCertificateKey] = certificate;\n        var result = await invoker.SendAsync(request, CancellationToken.None);	0
8336244	8334135	HTML Scraping with HTML Agility Pack	string imgValue = doc.DocumentNode.SelectSingleNode("//input[@id = \"img\"]").GetAttributeValue("value", "0");\nstring xValue = doc.DocumentNode.SelectSingleNode("//input[@id = \"x\"]").GetAttributeValue("value", "0");\nstring yValue = doc.DocumentNode.SelectSingleNode("//input[@id = \"y\"]").GetAttributeValue("value", "0");	0
9298127	9294670	How to enable/add a BackButton on the NavigationController?	public class MyViewController : DialogViewController\n{\n    public MyViewController\n        : base(new RootElement("foo"), true)\n    {\n\n    }\n}	0
32152484	32152447	How I Get Treeview Multiple Node value in asp.net c#?	selectedNode.Nodes	0
14501381	14501196	Selecting elements from XML file using LINQ	var xdoc = XDocument.Load("buildings.kml");\nXNamespace kml = "http://www.opengis.net/kml/2.2";\nvar buildings = xdoc.Root.Elements(kml + "Document")\n                    .Select(d => new Building {\n                        BuildingName = (string)d.Element(kml + "name")\n                    }).ToList();	0
10352888	10352775	Accessing a file from my dll	// Gets a reference to the same assembly that \n// contains the type that is creating the ResourceManager.\nSystem.Reflection.Assembly myAssembly = typeof(Program).Assembly;\n\n// Gets a reference to a different assembly.\nSystem.Reflection.Assembly myOtherAssembly;\nmyOtherAssembly = System.Reflection.Assembly.Load("ResourceAssembly");\n\n// Creates the ResourceManager.\nSystem.Resources.ResourceManager myManager = new \n   System.Resources.ResourceManager("ResourceNamespace.myResources", \n   myAssembly);\n\n// Retrieves String and Image resources.\nUnmanagedMemoryStream x = myManager.GetStream("StringResource");	0
24691550	24690744	How can I compare text from two different web pages and compare it?	public class TestClass\n{\n    public static void Main(string[] args)\n    {\n        bool isEqual = DownloadString("www.abc.com") == DownloadString("www.xyz.com")\n        // do whatever you want with it\n    }    \n\n    private static string DownloadString(string address)\n    {\n        using (WebClient client = new WebClient())\n        {\n            return client.DownloadString(address);\n        }\n    }\n}	0
3735327	3734994	Making test run in parallel	// not a real code\nforeach(Test t in myTetsts.AsParallel())\n{\n   t.run();\n}	0
12667987	12667924	How to break an array in 2 arrays in c#?	var a = new[] {1,2,3,4,5,6,7,8,9,10}\nvar a1 = a.Take(a.Length / 2).ToArray();\nvar a2 = a.Skip(a.Length / 2).ToArray();	0
11931064	11930367	Failed when creating a skeleton WiX extension	using Microsoft.Tools.WindowsInstallerXml;	0
12714606	12713708	How to check if only one Role is matching?	public ViewResult Index()\n{\n   var roleFilter = Roles.GetRolesForUser().First(r => !r.equals("Admin"));\n\n   return View(new UserViewModel\n                {\n                    Users = _userService.FindAll().Where(x => Roles.GetRolesForUser(x.UserName).Contains(roleFilter)),\n                    Roles = new [] {roleFilter}\n                });\n}	0
2066253	2064030	What's the best way to return an "Unauthenticated" message from a controller action to an Ajax request object?	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method)]\nsealed public class RedirectIfUserNotLoggedOnAttribute : ActionFilterAttribute\n{\npublic override void OnActionExecuting (ActionExecutingContext filterContext)\n  {\n    if (!IsUserLoggedOn)\n        {\n          filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new\n                                                                                      {\n                                                                                        controller = "User",\n                                                                                        action = "WarnLogOutAsJson",\n                                                                                      }));\n        }\n}\n}	0
6335229	6335168	How can I add a specified number of list elements to an ILIST?	public class ABC \n{\n    public ABC(int count)\n    {\n       if (count < 1) \n       {\n           throw new ArgumentException("count must be a positive number", "count");\n       }\n        _textfillerDetails = Enumerable\n            .Range(1, count)\n            .Select(x => new TextDetail())\n            .ToList();\n    }\n\n    public IList<TextFillerDetail> TextFillerDetails { get { return _textfillerDetails; } }        \n    private List<TextFiller> _textfillerDetails;\n}	0
3516366	3516262	Where can I learn how to deploy ASP.NET 4 MVC 2 applications to IIS7?	%windir%\Microsoft.NET\Framework64\v4.0.30128\aspnet_regiis.exe -ir	0
7567583	7553423	C# PropertyGrid - Check if a value is currently beeing edited	public static bool IsInEditMode(PropertyGrid grid)\n{\n    if (grid == null)\n        throw new ArgumentNullException("grid");\n\n    Control gridView = (Control)grid.GetType().GetField("gridView", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(grid);\n    Control edit = (Control)gridView.GetType().GetField("edit", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(gridView);\n    Control dropDownHolder = (Control)gridView.GetType().GetField("dropDownHolder", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(gridView);\n\n    return ((edit != null) && (edit.Visible & edit.Focused)) || ((dropDownHolder != null) && (dropDownHolder.Visible));\n}	0
20267713	20267606	How to get only the first value from a flags enum value and get it in the order they were added	if ((int)sT != 0 && (sT & types) == sT) list.Add(sT);	0
16589594	16588844	Using foreach loop with DataList on Page Load	shoplistview.Items.Count == 0	0
24473307	24291249	DialogPage - string array not persisted	[Category("General")]\n    [DisplayName("Foos")]\n    [Description("Bla Foo Bla")]\n    [TypeConverter(typeof(FoosCoverter))]\n    public string[] Foos { get; set; }	0
182557	182529	Creating controls within a Loop	for (int i = 0; i < 7; i++)\n    {\n\n        TableCell tCell = new TableCell();\n        TextBox txt = new TextBox();\n        tCell.Controls.Add(txt);\n        tRow.Cells.Add(tCell);\n\n    }	0
1946407	1946371	is it possible to dynamically resize the lable in c# without changing the length of text?	AutoSize = false	0
19351001	19350879	How do I Instantiate Instances of a Class That Is In Another Project Within My Solution?	using HelpDeskBusinessDataObjects	0
5518061	5518039	Choosing a random string in C# for WP7	var randomGenerator = new Random();\n\nstring[] prizes = { "vacation to Hawaii with all expenses covered",\n                    "used glue stick",\n                    "pile of dog dung",\n                    "vacation to Europe with all expenses covered" };\n\nstring firstDoor = prizes[randomGenerator.Next(prizes.Length)];\nstring secondDoor = prizes[randomGenerator.Next(prizes.Length)];\nstring thirdDoor = prizes[randomGenerator.Next(prizes.Length)];	0
20889829	20889812	How to avoid null checking in a foreach body?	foreach (MyObject obj in list.Where(o => o != null))\n    Console.WriteLine(obj.Value);	0
32122612	32122041	How to paste formatted text in textbox	public String RetrieveClipboardHtmlText(String replacementHtmlText)\n{\n    String returnHtmlText = null;\n    if (Clipboard.ContainsText(TextDataFormat.Html))\n    {\n        returnHtmlText = Clipboard.GetText(TextDataFormat.Html);\n    }\n    return returnHtmlText;\n}	0
5002391	4626459	Linq-to-sql POCO - insert fails because of NULL associations	[Table(Name = "Locations")]\npublic class Location\n{\n\n    [Column(IsPrimaryKey = true, IsDbGenerated = true, AutoSync = AutoSync.OnInsert)]\n    internal int LocationId { get; set; }\n\n    [Column]        \n    public int? SiteId { get; set; }\n\n    [Association(ThisKey = "SiteId", OtherKey = "SiteId", IsForeignKey = true)]        \n    public Site Site\n    {\n        get;\n        set;\n    }\n\n}	0
12670945	12670912	SQL Escaping character for quotation mark	SET @vSQL = 'UPDATE Clients SET LastOnline=GETDATE(), Status=''Open'' WHERE ClientID IN (' + @ClientIDs  + ')';	0
9520284	9517491	how do i send folder with its contents (subfolder/files) to server-client side?	public void SendFolder(string srcPath, string destPath)\n    {\n        string dirName = Path.Combine(destPath, Path.GetFileName(srcPath));\n        CreateDirectory(dirName);  // consider that this method creates a directory at the server\n        string[] fileEntries = Directory.GetFiles(srcPath);\n        string[] subDirEntries = Directory.GetDirectories(srcPath);\n        foreach (string filePath in fileEntries)\n        {\n            Send(srcPath, dirName);\n        }\n        foreach (string dirPath in subDirEntries)\n        {\n            SendFolder(dirPath, dirName);\n        }\n    }	0
3952824	3916099	How to save selected item from dropdownlist in asp.net mvc2	string EmplyeeId = Request["EmplyeeId "];	0
30969547	30969271	async methods in callbacks	public async void Run(IBackgroundTaskInstance taskInstance)\n{\n    BackgroundTaskDeferral _deferral = taskInstance.GetDeferral();\n\n    Debug.WriteLine("Test");\n        Debug.WriteLine(DateTime.Now.ToString("g"));\n\n        StorageFolder dataFolder = ApplicationData.Current.LocalFolder;\n        StorageFile logFile = await dataFolder.CreateFileAsync("logFile.txt", CreationCollisionOption.OpenIfExists);\n\n        IList<string> logLines = await FileIO.ReadLinesAsync(logFile);\n\n        foreach( var s in logLines )\n        {\n            Debug.WriteLine(s);\n        }\n\n        logLines.Add(DateTime.Now.ToString("g"));\n        if( logLines.Count > 5 )\n        {\n            logLines.RemoveAt(0);\n        }\n\n        await FileIO.AppendLinesAsync(logFile, logLines);\n\n    _deferral.Complete(); \n}	0
10402039	10401942	Skip reading xml elements that are inside a certain parent node	XmlDocument doc = new XmlDocument();\ndoc.Load("path.xml");\nforeach (XmlElement  pointCoord in doc.SelectNodes("/place/point/coordinate"))\n{\n    /Do something\n}	0
23991553	23991359	In C# can you split a string into variables?	public static class MyPhpStyleExtension\n{\n    public void SplitInTwo(this string str, char splitBy, out string first, out string second)\n    {\n        var tempArray = str.Split(splitBy);\n        if (tempArray.length != 2) {\n            throw new NotSoPhpResultAsIExpectedException(tempArray.length);\n        }\n\n        first = tempArray[0];\n        second = tempArray[1];\n    }\n}	0
6334689	6334632	How can I use IList with a master/detail type class?	public IList<TextFillerDetail> TextFillerDetails        \n{            \n    get { return _textfillerDetails; }\n}        \n\nprivate List<TextFiller> _textfillerDetails = new List<TextFiller>();	0
14673047	14672164	Binding XAML grid to an array	Grid.Column="{Binding [0], Source={x:Static Member=local:GridProperties.gridColumn}}"	0
12474838	12474366	Split string to dictionary as key,list	//short example string - may contain 1000's     \nstring newstr = ...;\n\nstring[] keysAndValues = newstr.Split(':');\nvar mydictionary = new Dictionary<string, List<string>>(keysAndValues.Length);\nforeach (string item in keysAndValues)     \n{         \n    List<string> list = new List<string>(item.Split(','));         \n    mydictionary.Add(list[0], list);\n    // remove key from list to match Jon Skeet's implementation\n    list.RemoveAt(0);\n}	0
6335491	6335445	Convert int to Color in winforms	var argb = Convert.ToInt32(\n    ((DataRowView)this.dataGridView1.Rows[e.RowIndex].DataBoundItem)["Color"]);\nColor = Color.FromArgb(argb);	0
32314288	32314202	Sort List Object based on Unique key using linq	var result = list.GroupBy(x => new { x.FirstName, x.LastName, x.Mobile, x.Email })\n                 .Select(x => new \n                                 {\n                                    Id = String.Join("|",x.Select(z => z.Id)),\n                                    FirstName = x.Key.FirstName\n                                    LastName = x.Key.LastName,\n                                    Mobile = x.Key.Mobile,\n                                    Email = x.Key.Email\n                                 });	0
23777984	23777951	Define a method with generic param of type M<T> in C#	class SomeClass\n{\n    public void DoSomething<M,T>(M instance) where T : Base \n                                             where M : GenericClass<T>\n    {\n       // Do something...\n    }\n}	0
18530358	18529761	Convert object to another	public B Convert<A, B>(A element) where B : A, new()\n    {\n        //get the interface's properties that implement both a getter and a setter\n        IEnumerable<PropertyInfo> properties = typeof(A)\n            .GetProperties()\n            .Where(property => property.CanRead && property.CanWrite).ToList();\n\n        //create new object\n        B b = new B();\n\n        //copy the property values to the new object\n        foreach (var property in properties)\n        {\n            //read value\n            object value = property.GetValue(element);\n\n            //set value\n            property.SetValue(b, value);\n        }\n\n        return b;\n    }	0
5408193	5408122	how to save HTML in byte[] as Image??? c#	var bytes = Encoding.Default.GetBytes(htmlString);	0
7568216	7543846	How to remove additional padding from a WPF TextBlock?	textBlock.LineStackingStrategy = LineStackingStrategy.BlockLineHeight,\ntextBlock.LineHeight = 20 // Or some other value you fancy.	0
5513253	5499843	I want to sort index in Lucene.net how I can make descending of this one in c#?	var sort = new Lucene.Net.Search.Sort(\n    new Lucene.Net.Search.SortField("date", Lucene.Net.Search.SortField.LONG),\n    true);	0
18625087	18625086	How to set Image Source in C# to XAML Static Resource programmatically?	TypeIcon.Source = (ImageSource) Resources["Project"];	0
18128579	17714038	How do I filter for a custom column?	public static Expression<Func<T, bool>> LikeLambdaString<T>(string propertyName, string value)\n{\n    var linqParam = Expression.Parameter(typeof(T), propertyName);\n    var linqProp = GetProperty<T>(linqParam, propertyName);\n\n    var containsFunc = Expression.Call(linqProp,\n        typeof(string).GetMethod("Contains"),\n        new Expression[] { Expression.Constant(value) });\n\n    return Expression.Lambda<Func<T, bool>>(containsFunc,\n        new ParameterExpression[] { linqParam });\n}	0
15871975	15870780	Check For Third-Party App Installation	IEnumerable<Package> apps = Windows.Phone.Management.Deployment.InstallationManager.FindPackagesForCurrentPublisher();\napps.First().Launch(string.Empty);	0
6994793	6994320	Compare items in different dictionaries with same key using LINQ	var result = _expectations.Where(e => _properties.Any(p => p.Key == e.Key && e.Value.Matches(p.Value)));	0
24681233	24681040	Is there a way to wrap an object up as a ConcurrentObject?	Lazy<T>	0
5454725	5454670	Select entries where only a Foreign Key is present for that ID	var results = from r in dc.Registration\n              join o1 in dc.Optional1 on r.RegistrationID equals o1.RegistrationID\n              select r;	0
1746924	1746701	Export DataTable to Excel File	dt = city.GetAllCity();//your datatable\n    string attachment = "attachment; filename=city.xls";\n    Response.ClearContent();\n    Response.AddHeader("content-disposition", attachment);\n    Response.ContentType = "application/vnd.ms-excel";\n    string tab = "";\n    foreach (DataColumn dc in dt.Columns)\n    {\n        Response.Write(tab + dc.ColumnName);\n        tab = "\t";\n    }\n    Response.Write("\n");\n    int i;\n    foreach (DataRow dr in dt.Rows)\n    {\n        tab = "";\n        for (i = 0; i < dt.Columns.Count; i++)\n        {\n            Response.Write(tab + dr[i].ToString());\n            tab = "\t";\n        }\n        Response.Write("\n");\n    }\n    Response.End();	0
27390708	27390670	'where' property in one of 2 number ranges	ListOfItems = store.Items.Where(p => (p.Type > 159 && p.Type < 169) || (p.Type > 220 && p.Type < 241)).ToList()	0
9635849	9635076	Permutations using same letters	static IEnumerable<string> GetVariations(string s)\n    {\n        int[] indexes = new int[s.Length];\n        StringBuilder sb = new StringBuilder();\n\n        while (IncrementIndexes(indexes, s.Length))\n        {\n            sb.Clear();\n            for (int i = 0; i < indexes.Length; i++)\n            {\n                if (indexes[i] != 0)\n                {\n                    sb.Append(s[indexes[i]-1]);\n                }\n            }\n            yield return sb.ToString();\n        }\n    }\n\n    static bool IncrementIndexes(int[] indexes, int limit)\n    {\n        for (int i = 0; i < indexes.Length; i++)\n        {\n            indexes[i]++;\n            if (indexes[i] > limit)\n            {\n                indexes[i] = 1;\n            }\n            else\n            {\n                return true;\n            }\n        }\n        return false;\n    }	0
10767689	10745115	in xna how do i properly reference the vector2 coordinates in relation to origin?	int x = (int) me.position.X + me.width/2; \nint y = (int) me.position.Y + me.height/2; \nint dist = 2; \nme.moveTo(rand.Next(x-dist,x+dist), rand.Next(y-dist, y+dist), running); //kick off moveTo function	0
21600850	21600585	Using url in C#	String url = @"http://www.example.com/";\n  Byte[] dat = null;\n\n  // In case you need credentials for Proxy\n  if (Object.ReferenceEquals(null, WebRequest.DefaultWebProxy.Credentials))\n    WebRequest.DefaultWebProxy.Credentials = CredentialCache.DefaultCredentials;\n\n  using (WebClient wc = new WebClient()) {\n    // Seems that you need raw data, Byte[]; if you want String - wc.DownLoadString(url);\n    dat = wc.DownloadData(url);\n  }	0
21308029	21307900	How to check if registration number includes string - c# console app	do {\n     Console.WriteLine("Enter reg. number: ");\n     newStudent.regNumber = Console.ReadLine();\n     if (newStudent.regNumber.Length == 7 && newStudent.regNumber[0] == 'E'){\n         break;\n     }\n     else\n     {\n         Console.WriteLine("wrong reg number");\n     }\n } while (true);	0
11824299	11823867	Find the index of a string in a datagridview row?	FirstOrDefault()	0
16129886	16129799	Event action of a specific label from an array of labels c#	_arr[i] = new Label();   \n _arr[i].Click += (s, e) => MessageBox.Show("Message");	0
10190023	10184151	populating datagridview with files in multiple subfolderse	string filePath = @"C:\Users\me\Documents\MASTERDIRECTORY\Folder7"\n\n                foreach (string Folder in Directory.GetDirectories(filePath))\n                {\n\n                  foreach (string file in Directory.GetFiles(Folder))\n                     {\n                       // here you can grab the log file path and add it to you Gridview\n                     }\n\n                }	0
13205389	13101714	How can I create a temporary file to cache startup work for a library?	var cacheDir = Path.Combine(\n    Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData), \n    "MyApplicationName");	0
343886	343869	Taking out all classes of a specific namespace	public static IEnumerable<Type> GetTypesFromNamespace(Assembly assembly, \n                                               String desiredNamespace)\n{\n    return assembly.GetTypes()\n                   .Where(type => type.Namespace == desiredNamespace);\n}	0
3486923	3486898	How Can I Put Escape Character before Special Characters using C#?	string s = File.ReadAllText("input.txt");\nstring empty = "buildLetter.Append(\"\").AppendLine();" + Environment.NewLine;\ns = s.Replace(empty, "");\ns = Regex.Replace(s, @"(?<="").*(?="")",\n         match => { return match.Value.Replace("\"",  "\\\""); }\n    );	0
1825577	1825568	Append a Lists Contents to another List C#	GlobalStrings.AddRange(localStrings);	0
33618021	33615847	Traversing Specific XML Nodes and Modifying Values	var mobileNumbers = testxml.Descendants("data").Select(x => new {\n                        mobilenumber = x.Element("mobilenumber").Value,\n                        address = x.Element("address").Value,\n                    }).ToList();	0
10694158	10694121	Using RegEx to Insert Character before Matches	Regex.Replace(input, @"[abc]", m => string.Format(@"\{0}", m.Value))	0
24590563	24579116	How to simplify InputBindings in XAML?	var keys = new List<Key> { Key.Space, Key.OemPeriod, Key.D1, [...]};\nforeach(var key in keys)\n{\n     this.InputBindings.Add(new KeyBinding() { Command = MyCommandClass.KeyboardCommand, CommandParameter = key});\n]	0
3463693	3463144	Can an ICriteria return an IDictionary instead of a List<DTO>?	var result = _session.CreateCriteria...\n             .List<object[]>\n             .ToDictionary(x => (int)x[0], x => (int)x[1]);	0
14734156	14733752	How to generate 8 digits UNIQUE & RANDOM number in C#	Random rnd = new Random();\nint myRandomNo= rnd.Next(10000000, 99999999); // creates a 8 digit random no.	0
31110860	31108833	Entity Framework 6 Insert data with foreign keys into azure sql database	context.BillingDetails.AddOrUpdate(billDetails);\n        context.Entry(billDetails).State = EntityState.Added;	0
284672	284420	(DataGridView + Binding)How to color line depending of the object binded?	dataGridView1.RowPostPaint += OnRowPostPaint;\n\nvoid OnRowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)\n{\n    MyObject value = (MyObject) dataGridView1.Rows[e.RowIndex].DataBoundItem;\n    DataGridViewCellStyle style = dataGridView1.Rows[e.RowIndex].DefaultCellStyle;\n\n    // Do whatever you want with style and value\n    ....\n}	0
21609727	21609154	GUID of IShellItem	MIDL_INTERFACE("43826d1e-e718-42ee-bc55-a1e261c37bfe")\n   IShellItem : public IUnknown\n   {\n       // etc..\n   }	0
20719804	20719691	Confused about how to read xml file	XmlDocument doc = new XmlDocument();\ndoc.Load("sample.xml");\nXmlElement root = doc.DocumentElement;\nXmlNodeList nodes = root.SelectNodes("some_node"); // You can also use XPath here\n\nforeach (XmlNode node in nodes)\n{ \n    listView1.Items.Add(node.Attributes["element name"].Value);\n    // or add here your listview items\n}	0
27416692	27416312	How to refine json by remove null values properties and zero (0) value properties from the c# object	public int? value { get; set;}	0
2149711	2149643	WCF communicating between services on a server	public class NotifyService\n    {\n        public static NotifyService DefaultInstace;\n\n        public NotifyService()\n        {\n            DefaultInstace = this;\n\n\n        }\n     ///.....SNIP......      \n   }	0
417224	417024	Can I get a reference to a pending transaction from a SqlConnection object?	public static void CallingFooBar()\n{\n   using (var ts=new TransactionScope())\n   {\n      var foo=new Foo();\n      foo.Bar();\n      ts.Complete();\n   }\n}	0
15633145	15632972	Retrieve Image from SQL Server & set to PictureBox Image Property	try\n{\n    // get image from object\n    byte[] _ImageData = new byte[0];\n    _ImageData = (byte[])_SqlRetVal;\n    System.IO.MemoryStream _MemoryStream = new System.IO.MemoryStream(_ImageData);\n    _Image = System.Drawing.Image.FromStream(_MemoryStream);\n}\ncatch (Exception _Exception)\n{\n    // Error occurred while trying to create image\n    // send error message to console (change below line to customize error handling)\n    Console.WriteLine(_Exception.Message);\n\n    return null;\n}	0
27697989	27697938	How do I know if my Button insersects with another button?	private void btPlayer_Click(object sender, EventArgs e)\n    {\n        foreach(Button btn in this.Controls.OfType<Button>())\n        {\n            if (!btn.Equals(btPlayer))\n            {\n                if (btPlayer.Bounds.IntersectsWith(btn.Bounds))\n                {\n                    Console.WriteLine("btPlayer intersects with " + btn.Name);\n                }\n            }\n        }\n    }	0
5802247	5801900	Serialize a object to the smallest UTF8 compatible size	0: a\n1: b\n..\n25: z\n26: 0	0
4743411	4743300	Wish to learn registry manipulations, its concepts right from basics	The Windows Registry in C#	0
5647965	5647922	Auto activate an item on select in a ListView	private void ListView1_ItemSelectionChanged(Object sender, ListViewItemSelectionChangedEventArgs e) \n{\n    ListView1_ItemActivate(sender, e);\n}	0
1248567	1248559	how to Creating buttons in a running application (runtime) plus its onclick event function using C#?	int y = 10;\nforeach (string name in names)\n{        \n    Button button = new Button();\n    button.Text = name;\n    button.Position = new Point(10, y);\n    y += 20;\n    button.Click += HandleButtonClick;\n    Controls.Add(button);\n}	0
23839084	23839029	Using a 2d array for user and passwords	class Credentials\n{\n  public string User { get; set; }\n  public string Password { get; set; }\n}	0
21201710	21201510	wrapping strings around each new line in a rich text box using C#	private void button1_Click(object sender, EventArgs e)\n{\n    var textInEachLine = richTextBox1.Text.Split(new string[] {"\n"}, StringSplitOptions.RemoveEmptyEntries);\n    string whereClause = string.Join("', '", textInEachLine).ToString();\n    MessageBox.Show(" IN ( '" + whereClause + "')");\n}	0
16434812	16434451	Set a zero point and if the value is lower or higher than this it is shown as -value or +value	int output(int deg, int zeropoint)\n    {\n        var relative = deg - zeropoint;\n        if (relative > 180)\n            relative -= 360;\n        else if (relative < -179)\n            relative += 360;\n        return relative;\n    }	0
3070058	3070041	How to get array of string from List<Tuple<int, int, string>>?	var strings = list.Select(item => item.Item3).ToArray();	0
30552894	30552712	How to use LINQ to group by multiple conditions in a C# List?	var groupedByBothConditions = lsEQData.GroupBy(x => new\n{\n    Range = ranges.FirstOrDefault(r => r > x.MagnitudeInMl),\n    IncEpicentre = x.IncEpicentre\n})\n.Select(g => new { g.Key,  TotalHits = g.Count().ToString()});	0
30341803	30340428	wp8 c sharp community create tables in sqlite	// The database path.   \npublic static string DB_PATH =Path.Combine(Path.Combine(ApplicationData.Current.LocalFolder.Path, "sample.sqlite"));   \n// The sqlite connection.   \nprivate SQLiteConnection dbConn = new SQLiteConnection(DB_PATH);\ndbConn.CreateTable<Task>();	0
878438	878302	Printing using Word Interop with Print Dialog	object nullobj = Missing.Value;\ndoc = wordApp.Documents.Open(ref file,\n                             ref nullobj, ref nullobj, ref nullobj,\n                             ref nullobj, ref nullobj, ref nullobj,\n                             ref nullobj, ref nullobj, ref nullobj,\n                             ref nullobj, ref nullobj, ref nullobj,\n                             ref nullobj, ref nullobj, ref nullobj);\n\ndoc.Activate();\ndoc.Visible = true;\nint dialogResult = wordApp.Dialogs[Microsoft.Office.Interop.Word.WdWordDialog.wdDialogFilePrint].Show(ref nullobj);\n\nif (dialogResult == 1)\n{\n    doc.PrintOut(ref nullobj, ref nullobj, ref nullobj, ref nullobj, \n                 ref nullobj, ref nullobj, ref nullobj, ref nullobj, \n                 ref nullobj, ref nullobj, ref nullobj, ref nullobj, \n                 ref nullobj, ref nullobj, ref nullobj, ref nullobj, \n                 ref nullobj, ref nullobj);\n}	0
4254031	4191311	Jquery Message Box After Postback	ClientScript.RegisterClientScriptBlock(typeof(Page), "yourKey", "$().ready(function () { csscody.alert('Hello')});", true);	0
27036839	27036699	how to convert a winform application to console application	static void Main(string[] args)\n{\n if (args.Length > 0)\n {\n    String paramValue1 = args[0];\n }\n}	0
16619868	16619609	Find string in file using regular expression	TextReader reader = new StreamReader(path);\n IEnumerable<string> data = this.ReadLines(reader);  \n\n foreach (var s in data){\n     // make sure its not null doesn't start with an empty line or something.\n     if (s != null && !string.IsNullOrEmpty(s) && !s.StartsWith("  ") && s.Length > 0){\n        s = s.ToLower().Trim();\n\n        // use regex to find some key in your case the "ID".\n        // look into regex and word boundry find only lines with ID\n        // double check the below regex below going off memory. \B is for boundry\n        var regex = new Regex("\BID\B");\n        var isMatch = regex.Match(s.ToLower());\n        if(isMatch.Success){ \n           // split the spaces out of the line.\n           var arr = s.split(' ');\n           var id = arr[1]; // should be second obj in array.\n\n        }\n\n     }\n }	0
22639412	22639120	How to save a coordinate list after app is tombstoned?	//Your custom GeoCoord container\n[DataContractAttribute]\npublic class GeoCoordContainer{\n  [DataMember]\n  public double lat = 0;\n\n  [DataMember]\n  public double lon = 0;\n\n  public GeoCoordContainer(Double lat, Double lon){\n    this.lat = lat;\n    this.lon = lon;\n  }\n}\n\n\n//Then in your Navigated from method\n  GeoCoordContainer cont = new GeoCoordContainer(MyGeoPosition.Lattitude,MyGeoPosition.Longitued);\n\n  //Now save it to the storage using EZ_Iso\n  EZ_Iso.IsolatedStorageAccess.SaveFile("MyLocation",cont);\n\n\n //To Retrieve it from storage \n  GeoCoordContainer cont = (GeoCoordContainer)EZ_Iso.IsolatedStorageAccess.GetFile("MyLocation",typeof(GeoCoordContainer));	0
24407185	24406730	how to read complex XML	string data = "<your xml data>";\nXElement elem = XElement.Parse(data);\n\nvar departments = elem.Descendants("dept").ToList();\nforeach (var dept in departments)\n{\n    var sLegal = dept.Elements("startDate")\n            .First(p => p.Attribute("type").Value == "legal").Value;\n    var eLegal = dept.Elements("endDate")\n            .First(p => p.Attribute("type").Value == "legal").Value;\n    var sOp = dept.Elements("startDate")\n            .First(p => p.Attribute("type").Value == "operational").Value;\n    var eOp = dept.Elements("endDate")\n            .First(p => p.Attribute("type").Value == "operational").Value;\n    var attr=dept.Attribute("operationalStatus");\n    var opStatus = attr == null ? "" : attr.Value;                \n    attr = dept.Attribute("primaryRole");\n    var primaryRole = attr == null ? "" : attr.Value;                \n    attr = dept.Attribute("depChangeDate");\n    var depChangeDate = attr == null ? "" : attr.Value;\n    //do something with the values\n}	0
13541532	13541298	Parsing Receipt XML with LINQ	bool result = xml.Descendants("ProductReceipt")\n    .Attributes().Single(x => x.Name == "ProductId")\n    .Value == productName;	0
32461277	32437488	How to perform PTZ programmatically for Axis Camera Control in C#	viewer.PTZControlURL = "http://ipaddress/axis-cgi/com/ptz.cgi";\nviewer.EnableAreaZoom = true;\nviewer.OneClicllkZoom = true;\nviewer.UIMode = "ptz-user-setting"	0
19186265	19185515	Formatting a localized date with out the year when the culture is variable	var d = new DateTime(2013, 10, 04);\nvar str = d.ToString("M");\nConsole.WriteLine(d);	0
27985000	27984923	How to call a servicestack service directly from c# code, with validation and optional request context	HostContext.ServiceController.ExecuteMessage(new Message<T>(requestDto), httpReq);	0
9182232	9169584	How to retrieve historical events after changes to Domain Event structure	public interface IUpgradeDomainEvents\n{\n    IEnumerable<IDomainEvent> Upgrade(IDomainEvent e, string id);\n}	0
3517543	3514945	Running a JavaScript function in an instance of Internet Explorer	this.Dispatcher.Invoke(DispatcherPriority.Normal, (Action)(() =>\n                {\n\n                        mshtml.HTMLDocument doc = ie.Document;\n\n                        mshtml.IHTMLWindow2 win = doc.parentWindow as IHTMLWindow2;\n                        win.execScript("init();", "javascript");\n\n\n                }));	0
6723477	6723447	How to launch an external process in C#, using a cmd window	ProcessStartInfo processToRunInfo = new ProcessStartInfo();    \nprocessToRunInfo.Arguments = "Arguments");\nprocessToRunInfo.CreateNoWindow = true;\nprocessToRunInfo.WorkingDirectory = "C:\\yourDir\\";\nprocessToRunInfo.FileName = "test.exe";\n//processToRunInfo.CreateNoWindow = true;\n//processToRunInfo.WindowStyle = ProcessWindowStyle.Hidden;\nProcess process = new Process();\nprocess.StartInfo = processToRunInfo;\nprocess.Start();	0
2317414	2317394	Convert a C# Method to return a boolean from a lambda expression	public bool IsFoobar(bool foo, bool bar)\n{\n    return db.Foobars.Any(fb => fb.foo == foo && fb.bar == bar);\n}	0
12398605	12398541	cURL call in C# with flag	// Create a request using a URL that can receive a post. \nWebRequest request = WebRequest.Create("http://localhost:8983/solr/update/extract?literal.id=doc1&commit=true");\n// Set the Method property of the request to POST.\nrequest.Method = "POST";\n// Create POST data and convert it to a byte array.\nstring postData = "myfile=@tutorial.html";\nbyte[] byteArray = Encoding.UTF8.GetBytes(postData);\n// Set the ContentType property of the WebRequest.\nrequest.ContentType = "application/x-www-form-urlencoded";\n// Set the ContentLength property of the WebRequest.\nrequest.ContentLength = byteArray.Length;	0
25843645	25843589	How i can convert date to text while exporting datagridview to excel?	DateTime.ParseExact("12/02/21 12:00 AM", "yy/MM/dd HH:mm tt", System.Globalization.CultureInfo.InvariantCulture).ToString("MMM. dd, yyyy HH:mm:ss");	0
28966065	28952157	Cannot access a .resw string resource in WinRT that uses a property dot notation through code?	var str = loader.GetString("Greeting/Text");	0
14963527	14963465	Fit action without parameters into Action<T>	ProcessItem<object>(subDir, dir.MinAge,\n    ignored => subDir.NoArgs(),\n    /* ignored */ null,\n    string.Format(Messages.NotDeletedFolder, subDir.FullName));	0
33331413	33310959	sha256.TransformBlock in Win10 Universal App	var message = new byte[] { 1, 2, 3 };\nvar s = new byte[32];\nbyte[] m;\nbyte[] x;\n\nusing (HashAlgorithm sha256 = SHA256.Create())\n{\n    m = sha256.ComputeHash(message);\n}\n\nusing (IncrementalHash sha256 = IncrementalHash.CreateHash(HashAlgorithmName.SHA256))\n{\n    sha256.AppendData(m);\n    sha256.AppendData(s);\n    x = sha256.GetHashAndReset();\n}	0
21693125	21692748	Parse and Extract Attributes from JSON	dynamic myJson = Json.Decode(myJsonString);\nforeach (var url in myJson.data.images.standard_resolution){\n//DO SOMETHING\n}	0
19066178	19066112	how to delete from selected items of listbox in asp.net	protected void listbox_mar_SelectedIndexChanged(object sender, EventArgs e)\n{\n    for (int i = 0; i < listbox_mar.Items.Count; i++)\n    {\n        if (listbox_mar.Items[i].Selected)\n        {\n            lbl_mar_cat.Text += listbox_mar.Items[i].Text+ " , " ;\n            listbox_mar.Items.Remove(listbox_mar.Items[i]);\n        }\n    }       \n}	0
13345746	13344793	How to filter entity framework result with multiple columns using a lambda expression	var query = dbConnection.Valgdata.GroupBy(u => u.omraade_id)\n      .Select(x => x.FirstOrDefault(y => x.Max(p => p.timestamp) == y.timestamp));	0
9140688	9140569	Difference between these two Singleton implementations	Lazy<T>	0
18602010	18601918	RichTextBox - Add text to top with multiple colors (only latest line is showing)	public void AddLog(Log log)\n{\n    try\n    {\n        richTextBox1.SelectAll();            \n        string oldText = this.richTextBox1.SelectedRtf;\n\n        this.richTextBox1.Text = log.User + ": " + log.Message + "\n";\n        this.richTextBox1.Select(0, log.User.Length);\n        this.richTextBox1.SelectionColor = Color.GreenYellow;\n        this.richTextBox1.Select(log.User.Length + 2, log.Message.Length);\n        this.richTextBox1.SelectionColor = Color.White;\n        this.richTextBox1.DeselectAll();\n        this.richTextBox1.SelectionStart = this.richTextBox1.TextLength;\n        this.richTextBox1.SelectedRtf = oldText;\n        this.richTextBox1.DeselectAll();\n\n    }\n    catch { }\n}	0
1792204	1792191	Will closing a FileStream close the StreamReader?	public class StreamReader : TextReader\n{\n    public override void Close()\n    {\n        this.Dispose(true);\n    }\n\n    protected override void Dispose(bool disposing)\n    {\n        try\n        {\n            if ((this.Closable && disposing) && (this.stream != null))\n            {\n                this.stream.Close();\n            }\n        }\n        finally\n        {\n            if (this.Closable && (this.stream != null))\n            {\n                this.stream = null;\n                this.encoding = null;\n                this.decoder = null;\n                this.byteBuffer = null;\n                this.charBuffer = null;\n                this.charPos = 0;\n                this.charLen = 0;\n                base.Dispose(disposing);\n            }\n        }\n    }\n}	0
5000997	5000966	How to convert an integer to fixed length hex string in C#?	value.ToString("X4")	0
21377163	21376997	Unable to pass data to method	data: {"data": JSON.stringify(arrayRows.data)}	0
7744950	7744835	C# datetime format and storing timezone info	string date = "2011-10-05T16:58:05.043GMT".Replace("GMT", "z");\nConsole.WriteLine(DateTime.Parse(date));	0
22401981	22385533	how to move serialized xml data to a entity framework code first database?	db.SaveChanges()	0
3076550	3073999	How to add a custom IOperationInvoker to every operation in an endpoint	public class MockOperationBehavior : BehaviorExtensionElement,  IOperationBehavior, IEndpointBehavior\n{\n  public void ApplyDispatchBehavior(ServiceEndpoint endpoint, EndpointDispatcher endpointDispatcher)\n  {\n     foreach (var op in endpoint.Contract.Operations)\n     {\n         op.Behaviors.Add(this);\n     }\n  }\n}	0
9997325	9997245	fastest way to sort list of strings	names.OrderBy(s => s.Split('-')[0]).ThenBy(s => s.Split('-')[1]);	0
6030084	6029766	How to create/update a LastModified field in EF Code First	public void SaveChanges()\n{\n    foreach (var entry in Context.ChangeTracker.Entries<ICreatedAt>().Where(x => x.State == EntityState.Added && x.Entity.CreatedAt == default(DateTime)))\n            entry.Entity.CreatedAt = DateTime.Now;\n\n    foreach (var entry in Context.ChangeTracker.Entries<ICreatedBy>().Where(x => x.State == EntityState.Added && x.Entity.CreatedBy == null))\n        entry.Entity.CreatedBy = ContextManager.CurrentUser;\n\n    foreach (var entry in Context.ChangeTracker.Entries<IModifiedAt>().Where(x => x.State == EntityState.Modified))\n        entry.Entity.ModifiedAt = DateTime.Now;\n\n    foreach (var entry in Context.ChangeTracker.Entries<IModifiedBy>().Where(x => x.State == EntityState.Modified))\n        entry.Entity.ModifiedBy = ContextManager.CurrentUser;\n\n    Context.SaveChanges();\n}	0
3144232	3144124	C#: Use a namespace for a specific block of code?	using rs = ReportService2005;\nusing re = ReportExecution;\n\n// ...\n\nrs.ParameterValue[] values = null;\nrs.DataSourceCredentials[] credentials = null;\nrs.ReportParameter[] parameters;\nre.ParameterValue v2 = ...;	0
13720797	13720484	Force GC to use another thread-context	A user of the Tao Framework implemented this idea with promising results. He wrote wrappers for OpenGL resources and implemented the disposable pattern like this:\nprivate void Dispose(bool manual)\n{\n    if (!disposed)\n    {\n        if (manual)\n        {\n             Gl.glDeleteTextures(1, ref _tid);\n             GC.SuppressFinalize(this);\n             disposed = true;\n        }\n        else\n        {\n            GC.KeepAlive(SimpleOpenGlControl.DisposingQueue);\n            SimpleOpenGlControl.DisposingQueue.Enqueue(this);\n        }\n    }\n}	0
19270445	19269077	IO filecannot access file in use	SmtpServer.Port = ****;\n        SmtpServer.Send(mail); \n        Mail.Dispose();\n        Console.WriteLine("Message Sent");	0
8321848	8321325	Accessing another row while in Gridview RowDataBound?	foreach (GridViewRow gvrow in GridView1)\n{\n    //loop through gridview's rows and find the row you're looking for\n}	0
1093722	1093581	NUL characters from Marshal.Copy in C#	string sTest1 = "abc\0\0def";\n\nstring sTest2 = sTest1.Replace("\0", "");\nConsole.WriteLine(sTest2);\n\nint iLocation = sTest1.IndexOf('\0');\nstring sTest3 = "";\nif (iLocation >= 0)\n{\n    sTest3 = sTest1.Substring(0, iLocation);\n}\nelse\n{\n    sTest3 = sTest1;\n}\nConsole.WriteLine(sTest3);\n\nConsole.ReadLine();	0
2357306	2357255	Detecting Duplicate Entries, Listview?	string newName = searcha.GetName().Name;\nif (!assemblyView.Items.Cast<ListViewItem>().Any(lvi => lvi.Text == newName))	0
26264100	26263611	Is it possible to save multiple radgrids in batch edit mode?	grid1.get_batchEditingManager().saveAllChanges();	0
22110266	22025907	Fill a ListView with LINQ SPROC result	var res = _linq.sp_SelectRecords(txtParam1.Text);\n            foreach (var order in res)\n            {\n                ListViewItem lvi = new ListViewItem(new[] { order.Cod_Prod, order.Description, order.Price.ToString() });\n                ListView1.Items.Add(lvi);\n            }	0
369250	369241	How do I convert C# characters to their hexadecimal code representation	char ch = 'A';\nstring strOut = String.Format(@"\x{0:x4}", (ushort)ch);	0
25665083	25665044	How to copy elements between arrays and at the same time know how many elements were copied?	Array.Copy	0
34426454	34424908	How can I determine if a certain number can be made up from a set of numbers?	private static readonly int Target = 1234567890;\nprivate static readonly List<int> Parts = new List<int> { 4, 7, 18, 32, 57, 68 };\n\nstatic void Main(string[] args)\n{\n    Console.WriteLine(Solve(Target, Parts));\n    Console.ReadLine();\n}\n\nprivate static bool Solve(int target, List<int> parts)\n{\n    parts.RemoveAll(x => x > target || x <= 0);\n    if (parts.Count == 0) return false;\n\n    var divisor = parts.First();\n    var quotient = target / divisor;\n    var modulus = target % divisor;\n\n    if (modulus == 0)\n    {\n        Console.WriteLine("{0} X {1}", quotient, divisor);\n        return true;\n    }\n\n    if (quotient == 0 || parts.Count == 1) return false;\n\n    while (!Solve(target - divisor * quotient, parts.Skip(1).ToList()))\n    {\n        if (--quotient != 0) continue;\n        return Solve(target, parts.Skip(1).ToList());\n    }\n\n    Console.WriteLine("{0} X {1}", quotient, divisor);\n    return true;\n}	0
13953616	13952932	Disable beep of enter and escape key c#	if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Tab))\n        {\n            Parent.SelectNextControl(textBox_Zakljucak, true, true, true, true);\n            e.Handled = e.SuppressKeyPress = true;\n        }	0
9083229	9083047	Open PDF in Adobe Reader, not in Browser	Response.ContentType = "application/pdf";\nResponse.AddHeader("content-disposition", "attachment; filename="+filePath); \nResponse.WriteFile(path);\nHttpContext.Current.ApplicationInstance.CompleteRequest();	0
18529378	18525030	How to keep shape in ILCube	pc.Limits.Set(new Vector3(-1,-1,-1), new Vector3(1,1,1));	0
7517895	7517377	Library of Custom Controls in Winforms	public class MyTextBox : TextBox\n{\n  public bool AllowDigitsOnly { get; set; }\n\n  protected override void OnKeyPress(KeyPressEventArgs e)\n  {\n    if (this.AllowDigitsOnly)\n    {\n      if (!char.IsDigit(e.KeyChar))\n        e.Handled = true;\n    }\n    base.OnKeyPress(e);\n  }\n}	0
15288163	15288134	How to display values only upto 2 decimal places	value.ToString("0.00");	0
6331137	6331094	How to concatenate keys with values?	string result=list.Select(w=>w.Key+";"+w.Value).Aggregate((c,n)=>c+","+n);	0
4478722	4478704	Enumerating through a Dictionary.KeyCollection in order	List<T>	0
15659236	15548147	White space cannot be stripped from input documents that have already been loaded. Provide the input document as an XmlReader instead	public static string Transform(XmlDocument doc, XmlDocument stylesheet)\n    {\n        try\n        {\n            System.Xml.Xsl.XslCompiledTransform transform = new System.Xml.Xsl.XslCompiledTransform();\n            transform.Load(stylesheet); // compiled stylesheet\n            System.IO.StringWriter writer = new System.IO.StringWriter();\n            XmlReader xmlReadB = new XmlTextReader(new StringReader(doc.DocumentElement.OuterXml));\n            transform.Transform(xmlReadB, null, writer);\n            return writer.ToString();\n        }\n        catch (Exception ex)\n        {\n            throw ex;\n        }\n\n    }	0
154263	154256	Is there a way to iterate through all enum values?	string[] names = Enum.GetNames (typeof(MyEnum));	0
8425560	8425501	How can I pass an empty string buffer that can be written to from native to c#?	delegate int GetNameFromDictionaryCallback(\n    UInt64 key, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder value);\n\npublic bool GetNameFromDictionary(UInt64 key, StringBuilder value)\n{\n    string s;\n    if (dict.TryGetValue(key, out s))\n    {\n        value.Append(s);\n        return true;\n    }\n    return false;\n}	0
6041315	6041268	Unified SQL getter with LINQ	Create procedure s_ProcTable\n@TableName varchar(128)\nas\n\ndeclare @sql varchar(4000)\n    select @sql = 'select count(*) from [' + @TableName + ']'\n    exec (@sql)\ngo	0
9984422	9984274	How do I update an ObservableCollection item's property from change in a WPF DataGrid?	public event PropertyChangedEventHandler PropertyChanged;\n    private void NotifyPropertyChanged(String info)\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(info));\n        }\n    }	0
22708561	22705583	how to not set to history list when open a new Tab on browser with javascript?	window.location.replace('url');	0
19748497	19748405	LEFT JOIN CTE as Lambda Expression / Query Expression	var Enumerable.Range(0,23)\n      .Join(MyTable.GroupBy(x => x.TableDate.Hour())\n             .Select(g => new { hour = g.Key, rev = g.Revenue.Sum() },\n            h => h,\n            g => g.hour,\n            (h , g) -> new { hour = h, revenue = g.rev });	0
11917983	11917953	Databind and trying to get index in Listview	alt='<%# "Banner_" + Container.ItemIndex %>'	0
2646159	2646140	Is there a way of using one method to handle others to avoid code duplication?	public Result<Boolean> CreateLocation(LocationKey key)\n{\n    LocationDAO locationDAO = new LocationDAO();\n    return WrapMethod(() => locationDAO.CreateLocation(key));\n}\n\n\npublic Result<Boolean> RemoveLocation(LocationKey key)\n{\n    LocationDAO locationDAO = new LocationDAO();\n    return WrapMethod(() =>  locationDAO.RemoveLocation(key));\n}\n\n\nstatic Result<T> WrapMethod<T>(Func<Result<T>> func)\n{\n    try\n    {\n        return func();\n    }\n    catch (UpdateException ue)\n    {\n        return new Result<T>(default(T), ue.Errors);\n    }\n}	0
2507914	2507843	Is it possible to coerce string values in xml to bool?	[XmlIgnore]\npublic bool Active { get; set; }\n\n[XmlAttribute("Active"), Browsable(false)]\n[EditorBrowsable(EditorBrowsableState.Never)]\npublic string ActiveString {\n    get { return Active ? "Yes" : "No"; }\n    set {\n        switch(value) {\n            case "Yes": Active = true; break;\n            case "No": Active = false; break;\n            default: throw new ArgumentOutOfRangeException();\n        }\n    }\n}	0
3404626	3404567	Move to previous textbox from current by pressing backspace	foreach(var tbox in new[]\n     {\n         tbox0, tbox1, tbox2\n     })\n{\n    tbox.KeyPress += (sender,e) => keypressed(sender,e);\n}\n\nprivate void keypressed(object sender, KeyPressEventArgs e)\n{\n    if (e.KeyChar == (char)Keys.Back)\n        ((Control)sender).GetNextControl((Control)sender, false).Select(); // .Focus()\n}	0
13494071	13494046	Ordering a Grouped Result in C#	var groups = from employee in employees\n             group employee by employee.ReportsTo into g\n             orderby g.Key\n             select g;	0
11982637	11981402	Get the nodes selected in treeview	private List<string> SelectedNodes = new List<string>();\n\nprivate void GetSelectedNodeText(NodeCollection nodes)\n{\n    foreach (Node node in nodes)\n    {\n        if (node.IsChecked != true && node.IsChecked != false)\n        {\n            SelectedNodes.Add(node.Text + "_" + GetSelectedChildNodeText(node.ChildNodes));\n        }\n        else if (node.IsChecked == true)\n        {\n            SelectedNodes.Add(node.Text);\n        }\n    }\n}\n\nprivate string GetSelectedChildNodeText(NodeCollection nodes)\n{\n    string retValue = string.Empty;\n\n    foreach (Node node in nodes)\n    {\n        if (node.IsChecked != true && node.IsChecked != false)\n        {\n            retValue = node.Text + "_" + GetSelectedChildNodeText(node.ChildNodes);\n        }\n        else if (node.IsChecked == true)\n        {\n            retValue = node.Text;\n        }\n    }\n\n    return retVal;\n}	0
27629201	27629182	Remove text after point in a string	string input = "abcdefg@fedcba";\nstring result = input.Substring(0, input.IndexOf('@'));	0
753804	753645	How do I get the correct IP from HTTP_X_FORWARDED_FOR if it contains multiple IP Addresses?	X-Forwarded-For: client1, proxy1, proxy2, ...	0
7111654	7110682	How to Reduce Congestion When Uploading Images to SharePoint	private static void uploadImage()\n        {\n            try\n            {\n\n                foreach (var img in lImageSet)\n                {\n                    Console.WriteLine("Image Name: {0}", img.getName());\n                }\n\n                foreach (var img in lImageSet)\n                {\n                    //Counter to track the number of images that have been uploaded\n                    i++;\n\n\n                    //For every 10 images that are uploaded, to reduce congestion, log out of SharePoint and log back in.\n                    if (i % 10 == 0)\n                    {\n                        clientContext.Dispose();\n                        sharepointLogin();\n                    }\n\n                    ....	0
23586142	23586041	Pause between repeats in an animation in WPF	var fadeInOutAnimation = new DoubleAnimation()\n{\n    From = 1,\n    To = 0,\n    Duration = TimeSpan.FromSeconds(1),\n};\n\nvar storyboard = new Storyboard\n{\n    Duration = TimeSpan.FromSeconds(2),\n    AutoReverse = true,\n    RepeatBehavior = RepeatBehavior.Forever\n};\n\nStoryboard.SetTarget(fadeInOutAnimation, MyCanvas);\nStoryboard.SetTargetProperty(fadeInOutAnimation,\n                             new PropertyPath(Canvas.OpacityProperty));\n\nstoryboard.Children.Add(fadeInOutAnimation);\nMyCanvas.BeginStoryboard(storyboard);	0
19029358	19027394	Access column values from a particular sheet, from multiple excels	decimal returnVal = 0;\n        for (int i = 1; i < rowused; i++) //NB: off-by-one error here? Shouldn't it be from 1 to <= rows ?\n        {\n            cRng = (Excel.Range)xlWorkSheet.Cells[i, rngResult.Column];\n            if (cRng != null)\n            {\n                decimal currentVal;\n                if( decimal.TryParse(cRng.Value2.ToString(), out currentVal) )\n                    returnVal += currentVal;\n            }\n        }\n        return returnVal.ToString();	0
27151484	27148341	How to block one specific Key in Windows Phone 8.1	private void TextBox_KeyDown(object sender, KeyRoutedEventArgs e)\n{\n    if (e.Key == (VirtualKey)(189))\n    {\n         e.Handled = true;\n    }\n}	0
9593061	9592963	How do I use Linq to read XML	var detail = (from x in result.Descendants("Transaction") \n                          select new { \n                              TransactionID = x.Element("TransactionID").Value, \n                              Frequency =  x.Element("Frequency").Value,\n                              Amount = x.Element("Amount").Value, \n                              Email = x.Element("Email").Value,\n                              Status = x.Element("Status").Value })\n                              .First();	0
23541536	23541340	How to run Application with multiple parameters?	MyProcess.StartInfo.Arguments = "\"this argument has spaces\"";	0
19367757	19366715	Converting a stored procedure to a LINQ query	var query = from Apps in objApps\n            join ratings in objRatings\n              on Apps.AppId equals ratings.AppId\n            where ratings.RatingGiven == 1 \n            group Apps by Apps.AppId into g\n            select new { AppId = g.AppId, ItemCount = g.Count() }	0
18179472	18179252	how can I use handle Verbatim String Literals?	foreach (string Items in listBox39.Items)\n{\n    using (OracleCommand crtCommand = new OracleCommand(@"SELECT  REGEXP_REPLACE ( REPLACE ( dbms_metadata.get_ddl ('PROCEDURE', '" + Items + @"'), '""" + txtSrcUserID.Text.ToUpper() + @""".'),'^\s+', NULL, 1, 0, 'm') FROM dual", conn1))\n    {\n\n    }\n}	0
6459213	6459050	Updating a datatable in c#	foreach(oldCount in absenceCount)\n{\n  DataRow[] dr = dt.Select("Student ID='" + ID + "' AND Absence Count != '" + oldCount);\n  dr[0].Delete();\n}	0
28997406	28997339	Populating an array with values from list check boxes	protected void Button1_Click(object sender, EventArgs e)\n    {\n\n    var test = new List<string>();\n\n    foreach (ListItem item in CheckBoxList1.Items)\n    {\n\n        if (item.Selected)\n        {\n            // oneSelected = true;\n\n            test.Add(item.Value);\n\n            Response.Write("<script LANGUAGE='JavaScript' >alert('"+item.Value+"')</script>");\n\n        }\n\n\n    }\n }	0
290517	290459	Why would someone use Button instead of LinkButton control in navigation	.linkButton\n{\n   background-color: transparent;\n   border-style: none;\n   color: /* Something nice */\n   cursor: pointer;\n   text-align: left;\n   text-decoration: underline;\n   display: table-cell;\n}	0
22170217	22167940	Cursor movement event outside of wpf window boundaries	private void InitializeCursorMonitoring()\n{\n    var point = Mouse.GetPosition(Application.Current.MainWindow);\n    var timer = new System.Windows.Threading.DispatcherTimer();\n\n    timer.Tick += delegate\n    {\n        Application.Current.MainWindow.CaptureMouse();\n        if (point != Mouse.GetPosition(Application.Current.MainWindow))\n        {\n            point = Mouse.GetPosition(Application.Current.MainWindow);\n            Console.WriteLine(String.Format("X:{0}  Y:{1}", point.X, point.Y));\n        }\n        Application.Current.MainWindow.ReleaseMouseCapture();\n    };\n\n    timer.Interval = new TimeSpan(0, 0, 0, 0, 100);\n    timer.Start();\n}	0
30127724	30127645	copy to clipboard from disabled Textbox	TextBox.IsReadOnly	0
15132799	15132740	Get filename of filepath	System.IO.Path.GetFileName(@"C:\Program Files\Internet Explorer\iexplore.exe")	0
20608789	20608701	Add XmlDocument in XmlDocument	var d1 = new XmlDocument();\nd1.LoadXml("<Tags><Tag name =\"1\"></Tag></Tags>");\n\nvar d2 = new XmlDocument();\nd2.LoadXml("<Tags><Tag name =\"2\"></Tag></Tags>");\n\nvar newNode = d1.ImportNode(d2.SelectSingleNode("/Tags/Tag"), true);\nd1.DocumentElement.AppendChild(newNode);\n\nConsole.WriteLine(d1.OuterXml);	0
6074917	6073202	Reading external XML via a proxy	XmlTextReader xml;\n                        WebRequest web;\n\n                        web = WebRequest.Create(xmlurl);\n                        if(Convert.ToBoolean(ConfigurationManager.AppSettings["behindproxy"].ToString()))\n                        {\n                            WebProxy prxy = new WebProxy();\n                            Uri prxyUri = new Uri("http://xxx:8080");\n\n                            prxy.Address = prxyUri;\n                            prxy.BypassProxyOnLocal = true;\n                            prxy.Credentials = new NetworkCredential(ConfigurationManager.AppSettings["proxyusername"].ToString(), ConfigurationManager.AppSettings["proxypassword"].ToString());\n                            web.Proxy = prxy;\n                        }\n\n                        var response = web.GetResponse().ToString();\n                        xml = new XmlTextReader(response);	0
27971827	27971428	Jquery trigger click after ajax call	window.location.href = obj.MessageLink;	0
17310806	17310795	C# button click event insert twice	sqlComm.ExecuteNonQuery();\nint lastID = (int)sqlComm.ExecuteScalar();	0
13035637	13035614	Return only values contained in list C#	List<CustomClass> SubList = ListOfObjects\n        .Where(obj => ListOfIDs.Contains(obj.ID))\n        .ToList();	0
16387730	16387602	C# Namegenarator brings 5 same letters	System.Random	0
1320666	1320059	How can I calculate the logical width of WPF visual element?	namespace MyCLRNamespace\n{\n    public partial class Window1 : Window\n    {\n        public Window1()\n        {\n            InitializeComponent();\n\n            Polygon MyPolygon = new Polygon();\n            MyPolygon.Points = new PointCollection {    new Point(100, 0),\n                                                        new Point(200, 200),\n                                                        new Point(0, 200)   };\n            //if (MyPolygon.IsMeasureValid == false)\n                MyPolygon.Measure(new Size( double.PositiveInfinity,\n                                            double.PositiveInfinity));\n\n            double PolyWidth = MyPolygon.DesiredSize.Width;\n        }\n    }\n}	0
2716501	2715546	NHibernate - Log items that appear in a search result	var searchResults = session.CreateCriteria<Product>()\n    //your query parameters here\n    .List<Product>();\nsession.CreateQuery(@"update Product set SearchCount = SearchCount + 1\n                      where Id in (:productIds)")\n       .SetParameterList("productIds", searchResults.Select(p => p.Id).ToList())\n       .ExecuteUpdate();	0
31737622	31728782	how to remove double quote and \ from nested value	select\n      new ItemManagementViewModel\n          {\n              FormType = value2.Name,\n              FormControllerID = value1.RecordId,\n              FormControllerName = value1.Name,\n              values = innerResult\n          }).ToList();	0
4238107	4238074	creating new xml file by C#	using System;\nusing System.Xml;\n\npublic class Sample {\n\n  public static void Main() {\n\n    // Create the XmlDocument.\n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml("<item><name>wrench</name></item>"); //Your string here\n\n    // Save the document to a file and auto-indent the output.\n    XmlTextWriter writer = new XmlTextWriter("data.xml",null);\n    writer.Formatting = Formatting.Indented;\n    doc.Save(writer);\n  }\n}	0
9946802	9946550	Getting pointer for first entry in an array	unsafe public void mf()\n   {\n      // Null-terminated ASCII characters in an sbyte array \n      sbyte[] sbArr1 = new sbyte[] { 0x41, 0x42, 0x43, 0x00 };\n      sbyte* pAsciiUpper = &sbArr1[0];   // CS0212\n      // To resolve this error, delete the previous line and \n      // uncomment the following code:\n      // fixed (sbyte* pAsciiUpper = sbArr1)\n      // {\n      //    String szAsciiUpper = new String(pAsciiUpper);\n      // }\n   }	0
27423663	27422605	Capture raw HTTPS request and response with FiddlerCore	var resHeaders = sess.oResponse.headers.ToString();\n    var resBody = sess.GetResponseBodyAsString();	0
17206402	17205669	MVC4 Match against optional count of parameters	routes.MapRoute(\n            name: "Default",\n            url: "{controller}/{action}/{param1}/{param2}",\n            defaults: new { controller = "home", action = "Index" , \n                param1 = UrlParameter.Optional, param2 = UrlParameter.Optional, }\n        );	0
26171845	26159289	Problems in implementing signal R in my project	[assembly: OwinStartup(typeof(CRMWeb.Startup))]\n\nnamespace CRMWeb\n{\n    public class Startup\n    {\n        public void Configuration(IAppBuilder app)\n        {\n            app.MapSignalR();\n        }\n    }\n}	0
31456967	31456753	If exists unallowed files, show messagebox with their name	DirectoryInfo directory = new DirectoryInfo(Directory.GetCurrentDirectory());\n        List<FileInfo> files = directory.GetFiles().ToList();\n        List<FileInfo> unAllowed = files.FindAll(f => !allowedFiles.Contains(f.Name));\n\n        if (unAllowed.Count > 0)\n        {\n            string notAllowedFiles = "";\n            unAllowed.ForEach(f => notAllowedFiles += f.Name + ",");\n            Message.Warning("Unallowed files found ! Please remove " + notAllowedFiles);\n            return;\n        }	0
8346094	8345998	How to cast Dictionary<string,MyClass> to Dictionary<string,object>	var addMethod = typeof(BagA).GetMethod("Add", new[] {typeof(string), typeof(BagB)});\naddMethod.Invoke(MyBagA, new object[] {"123", MyBagB});	0
4405726	4405703	Remove extra commas in C#	string result = Regex.Replace(input, ",+", ",").Trim(',');	0
8223195	8223031	add Image in code instead of xaml in windows phone	newGrid.SetRow(image, 0); \nnewGrid.SetColumn(image, 0); \nnewGrid.Children.Add(image); \n\n// Also \n\nLayoutRoot.Children.Add( newGrid );	0
18855120	18854901	How to get Range between TWO dates in Asp.Net..?	private List<DateTime> GetRange()\n {\n    var res = new List<DateTime>();\n    var start = DateTime.Parse(textBox1.Text);\n    var end = DateTime.Parse(textBox2.Text);\n    for (var date = start; date <= end; date = date.AddDays(1))\n         res.Add(date);\n\n    return res;\n }	0
14198704	14162392	Programmatically print to a PDF printer	XpsConverter.Convert("D:\\Example\\test.xps");	0
19381874	16940381	img tag with Resource Files and asp:literal	your_asp_literal.Text = "<img src='"+ GetGlobalResourceObject("your_resx_file", "your_picture_path").ToString() + "' alt='your_alt' height='42' width='42'/>";	0
1100178	1099949	Prevent DebuggerStepThroughAttribute from applying to my non-xsd-generated partial class?	[DebuggerStepThrough]\nstatic void DebuggerStepThroughInPartialClass()\n{\n   WrappedClass.NonDebuggerStepThrough();\n}\n\nclass WrappedClass{\n   static void NonDebuggerStepThroughInNewClass()\n   {\n      int bar = 0;\n      bar++;\n   }\n}	0
4406012	4405953	Avoiding "Access to a static member of a type via a derived type"	e.g. ErrorLogProvider.Instance.Write(something)	0
27758181	27758111	How to add row in datagridview with pre-data in c# winform?	private void btnaddcomp_Click(object sender, EventArgs e)\n{\n    DataTable ds = (DataTable)dgsetcompt.DataSource;\n\n    // Create a new row...\n    DataRow dr = ds.NewRow();\n\n    // Set the two fields\n    dr["code"] = this.dgsetcompt.Rows.Count + 1;\n    dr["date"] = new DateTime(2015, 1, 3);\n\n    // Add the newly created row to the Rows collection of the datatable\n    ds.Rows.Add(dr);\n\n    // Not needed\n    //dgsetcompt.DataSource = ds;\n}	0
2695395	2695345	How can I use plinq to fill an array with strings returned from my "FormatStatus" Method?	var formattedStatus = from status in _statusCollection.AsParallel()\n                      select FormatStatus(status);	0
14133746	13877710	Adding items to a listbox the ajax way	Textie.Attributes.Add("onblur", "javascript:CallMe('" + Textie.ClientID + "',        '" + Textie.ClientID + "')");	0
20171147	20171101	Trying to get data from a seperate class c# using string.format	StudentRecord student = new StudentRecord();\nstudent.ToString();	0
1054814	1054809	How do I parse a string using C# and regular expressions?	string str = @"Microsoft Windows XP Professional x64 Edition|C:\WINDOWS|\Device\Harddisk4\Partition1";\nstring str2 = str.Split('|')[0];	0
24139030	24138681	How to make a UIElement width relative to the parent container (in this case, StackPanel)?	var newLine = new Line();\n\n// some newLine initializing\n\nBinding binding = new Binding();\nbinding.Source = topStack;\nbinding.Path = new System.Windows.PropertyPath("ActualWidth");\nnewLine.SetBinding(Line.X2Property, binding);\n\ntopStack.Children.Add(newLine);	0
14129382	13995272	How do I express a query containing a WHERE..IN subquery using NHibernate's QueryOver API?	LineItem lineItemAlias = null;\nProduct productAlias = null;\n\nvar subQuery = QueryOver.Of<Order>()\n            .JoinAlias(x => x.LineItems, () => lineItemAlias)\n            .JoinAlias(() => lineItemAlias.Product, () => productAlias)\n            .Where(() => productAlias.Name == "foo")\n            .Select(Projections.Group<Order>(x => x.Id));\n\nvar results = Session.QueryOver<Order>()\n              .WithSubquery.WhereProperty(x => x.Id).In(subQuery)\n              .List();	0
11046523	11046285	IComparable Implementation	public static bool operator > (Circle x, Circle y) {\n   return x.CompareTo(y) > 0;\n}\n\n// and so on for the other operators	0
5911430	5910573	How to get CMD/console encoding in C#	int lcid = GetSystemDefaultLCID();\n        var ci = System.Globalization.CultureInfo.GetCultureInfo(lcid);\n        var page = ci.TextInfo.OEMCodePage;\n        // etc..\n\n    [System.Runtime.InteropServices.DllImport("kernel32.dll")]\n    public static extern int GetSystemDefaultLCID();	0
29459005	29458344	Delete files, copy the same named files from another folder C#	StringCollection filesToBeReplaced = new StringCollection();\n\nprivate void button2_Click(object sender, EventArgs e)\n{\nforeach (string file in Directory.GetFiles(@"\\" + textBox1.Text +      @"\\d$\\NSB\\Coalition\\EDU", "*.err").Where(item => item.EndsWith(".err")))\n{\n  //Now you have file names without extension        \n  filesToBeReplaced.Add(Path.GetFileNameWithoutExtension (file));\n      File.Delete(file);\n  }\n}\nprivate void CopyGoodFilesFromSource()\n{\n  foreach(string fileName in filesToBeReplaced)\n  {\n     string sourceFilePath = Path.Combine("YOUR FOLDER FOR GOOD FILES", \nPath.ChangeExtension(fileName,"Your Extension")) ;\n      string destinationPath = Path.Combine("Destination Folder",\nPath.ChangeExtension(fileName, "Your Extension in destination folder");\n\n     File.Copy(sourceFilePath , destinationPath, true);\n  }\n}	0
358685	358647	Programatically add user permission to a list in Sharepoint	// Assuming you already have SPWeb and SPList objects\n...\nSPRoleAssignment roleAssignment = new SPRoleAssignment("dom\\user", "user@dom", "user", "some notes");\nSPRoleDefinition roleDefinition = web.RoleDefinitions.GetByType(SPRoleType.Contributor);\nroleAssignment.RoleDefinitionBindings.Add(roleDefinition);\nif (!myList.HasUniqueRoleAssignments)\n{\n    myList.BreakRoleInheritance(true); // Ensure we don't inherit permissions from parent\n} \nmyList.RoleAssignments.Add(roleAssignment);\nmyList.Update();	0
8531263	8519200	How to check if string has a correct html syntax	string html = "<span>Hello world</sspan>";\n\nHtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml(html);\n\nif (doc.ParseErrors.Count() > 0)\n{\n   //Invalid HTML\n}	0
27248004	27247845	Passing a variable class object through to a class	public void updateDB(object paramobj)\n{\n    foreach(var prop in paramobj.GetType().GetProperties())\n    {\n           //grab\n    }\n    // update\n }	0
4973526	4973481	How do I read a file located in a same folder where my page resides in in ASP.NET?	File.OpenRead(Server.MapPath("foo.txt"));	0
13173882	13173827	open c# user control from another user control	YourCustomControl uc = null;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n     uc = new YourCustomControl();\n     this.Controls.Add(uc); // this represent the user control in which you want to add\n                            // You can add it in some container like Panel or GroupBox\n}	0
18562749	18546712	How to dispose bitmapsource	MemoryStream memoryStream = new MemoryStream();\n\n        byte[] fileBytes = File.ReadAllBytes(filepath);\n        memoryStream.Write(fileBytes, 0, fileBytes.Length);\n        memoryStream.Position = 0;\n\n        BitmapSource img = BitmapFrame.Create(memoryStream);\n        BitmapMetadata meta = (BitmapMetadata)img.Metadata;\n        DateTime datetaken = DateTime.Parse(meta.DateTaken);\n        System.IO.File.Delete(filepath);	0
11423912	11423537	How to add subitems to a ListView?	listView1.Columns.Add("Col1");\nlistView1.Columns.Add("Col2");\n\nstring[] strArrGroups = new string[3] { "FIRST", "SECOND", "THIRD" };\nstring[] strArrItems = new string[4] { "uno", "dos", "twa", "quad" };\nfor (int i = 0; i < strArrGroups.Length; i++)\n{\n    int groupIndex = listView1.Groups.Add(new ListViewGroup(strArrGroups[i], HorizontalAlignment.Left));\n    for (int j = 0; j < strArrItems.Length; j++)\n    {\n        ListViewItem lvi = new ListViewItem(strArrItems[j]);\n        lvi.SubItems.Add("Hasta la Vista, Mon Cherri!");\n        listView1.Items.Add(lvi);\n        listView1.Groups[i].Items.Add(lvi);\n    }\n}	0
25054056	25053897	How to search to search a file for string, display the line containing the string and also the 6 lines preceding it	static void Main(string[] args)\n{\n    Queue<string> lines = new Queue<string>();\n    using (var reader = new StreamReader(args[0]))\n    {\n        string line;\n        while ((line = reader.ReadLine()) != null)\n        {\n            if (line.Contains("error"))\n            {\n                Console.WriteLine("----- ERROR -----");\n                foreach (var errLine in lines)\n                    Console.WriteLine(errLine);\n                Console.WriteLine(line);\n                Console.WriteLine("-----------------");\n            }\n\n            lines.Enqueue(line);\n\n            while (lines.Count > 6)\n                lines.Dequeue();\n        }\n    }\n}	0
26536133	26535033	How to access a user property of a custom outlook mail item with Redemption in C#	string customPropertyNamespace = "http://schemas.microsoft.com/mapi/string/{00020329-0000-0000-C000-000000000046}/";    \nOutlook.Forlder oFolder = oPublicFolder.Folders["Babillards"].Folders["SYSOTI"].Folders["MEP"];\n\nRedemption.RDOSession session = new RDOSesssion();\nsession.MAPUIOBJECT = Application.Session.MAPIOBJECT;\nRedemption.RDOFolder rFolder = session.(RDOFolder)session.GetRDOObjectfromOutlookObject(oFolder);\nRedemption.RDOMail rMsg = rFolder.Items.Add("ipm.note.mep");\nrMsg.Fields[customPropertyNamespace + "prop1"] = "SomeText";\nrMsg.Save();\n//reopen in Outlook and display. Or you can use rMsg.Display()\nOutlook._MailItem oMep = Application.Session.GetItemFromID(rMsg.EntryID);\noMep.Display(false);	0
10556681	10556556	Insert all data of a datagridview to database at once	string StrQuery;\ntry\n{\n    using (SqlConnection conn = new SqlConnection(ConnString))\n    {\n        using (SqlCommand comm = new SqlCommand())\n        {\n            comm.Connection = conn;\n            conn.Open();\n            for(int i=0; i< dataGridView1.Rows.Count;i++)\n            {\n                StrQuery= @"INSERT INTO tableName VALUES (" \n                    + dataGridView1.Rows[i].Cells["ColumnName"].Value +", " \n                    + dataGridView1.Rows[i].Cells["ColumnName"].Value +");";\n                comm.CommandText = StrQuery;\n                comm.ExecuteNonQuery();\n            }\n        }\n    }\n}	0
30377505	30375934	How to display percentage with one decimal and manage culture with string.Format in C#?	bool hasDecimal = !percentage.Value.ToString("P1", CultureInfo.InvariantCulture).EndsWith(".0 %");\nstring percentageMask = hasDecimal ? "{0:P1}" : "{0:P0}";\nstring percentageValue = string.Format(CultureInfo.CurrentCulture, percentageMask, percentage);	0
27000702	26998311	how to change color of comboBoxEx Dotnetbar as form has StyleManager with different style	LinearGradientColorTable linGrBrush = new LinearGradientColorTable(\n           Color.DarkGray,\n           Color.DarkGray);\n\n        Office2007Renderer renderer = GlobalManager.Renderer as Office2007Renderer;\n        if (renderer == null) return;\n        Office2007ColorTable table = renderer.ColorTable;\n        // Stand-alone ComboBoxEx colors\n        Office2007ComboBoxColorTable comboColors = table.ComboBox;\n        comboColors.DefaultStandalone.Border = Color.DarkGray;\n        comboColors.DefaultStandalone.Background = Color.White;\n        comboColors.DefaultStandalone.ExpandText = Color.LightGray;\n        comboColors.DefaultStandalone.ExpandBorderInner = linGrBrush;\n        comboColors.DefaultStandalone.ExpandBorderOuter = linGrBrush;	0
27026913	27026373	Find Components Non Visual C#	private IEnumerable<Component> EnumerateComponents()\n{\n    return this.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)\n           .Where(f => typeof(Component).IsAssignableFrom(f.FieldType))\n           .Where(f => !typeof(Control).IsAssignableFrom(f.FieldType))\n           .Select(f => f.GetValue(this))\n           .OfType<Component>();\n}	0
9163246	9163178	how to display human readable xml in an asp.net mvc view page	protected string FormatXml(XmlNode xmlNode)\n{        \n    StringBuilder builder = new StringBuilder();\n\n    // We will use stringWriter to push the formated xml into our StringBuilder bob.\n    using (StringWriter stringWriter = new StringWriter(builder))\n    {\n        // We will use the Formatting of our xmlTextWriter to provide our indentation.\n        using (XmlTextWriter xmlTextWriter = new XmlTextWriter(stringWriter))\n        {\n            xmlTextWriter.Formatting = Formatting.Indented;\n            xmlNode.WriteTo(xmlTextWriter);\n        }\n    }\n\n    return builder.ToString();\n}	0
12401375	12401273	Change the default value of date in C# just by using the validation controls?	DateTime.Now.ToString("dd/MM/yyyy")));	0
33257613	33257347	How to use multiple file extensions using DataAnnotations?	[Required(ErrorMessage = "Choose an image"), \nFileExtensions(Extensions = "jpg,gif,png", ErrorMessage = "Error")]\npublic HttpPostedFileBase BannerData { get; set; }	0
680194	680174	Using keyboard shortcuts with LinkLabel controls	class BetterLinkLabel : LinkLabel\n{\n  protected override bool ProcessMnemonic( char charCode )\n  {\n    if( base.ProcessMnemonic( charCode ) )\n    {\n      // TODO: pass a valid LinkLabel.Link to the event arg ctor\n      OnLinkClicked( new LinkLabelLinkClickedEventArgs( null ) );\n      return true;\n    }\n    return false;\n  }\n}	0
25686130	25685934	How can I write the following lambda expression in one line?	expression = a => \n    (SearchResult.Name == null || a.Name == SearchResult.Name) && \n    (SearchResult.condition == null || Search.condition == (a.PersonType != null));	0
2450545	2450532	How To Get Type Info Without Using Generics?	Type t = obj.GetType();	0
31813987	31813266	How to get value from textBox by its name?	public Form1()\n        {\n            InitializeComponent();\n            B1.Text = "LOL";\n            Control ctl = FindControl(this, "B1");\n            if (ctl is TextBox)\n                listBox1.Items.Add(((TextBox)ctl).Text);\n        }\n        public static Control FindControl(Control parent, string ctlName)\n        {\n            foreach (Control ctl in parent.Controls)\n            {\n                if (ctl.Name.Equals(ctlName))\n                {\n                    return ctl;\n                }\n\n                FindControl(ctl, ctlName);\n            }\n            return null;\n        }	0
28601372	28586582	Multiple WPF applications in the same AppDomain	if (Application.Current == null)\n  {\n       MyApplication = new Application\n       {\n          ShutdownMode = ShutdownMode.OnExplicitShutdown\n       };\n   }\n   else\n       MyApplication = Application.Current;	0
6171222	6171202	C# parsing float from string	float.Parse(reader.Value.Replace(',', '.'), System.Globalization.CultureInfo.InvariantCulture);	0
24982374	24982272	Understanding the result of the decimal constructor with 5 arguments	Console.WriteLine(new decimal(0, 0, 0, false, 0)); //0\nConsole.WriteLine(new decimal(1, 0, 0, false, 0)); //1\nConsole.WriteLine(new decimal(0, 1, 0, false, 0)); //4294967296\nConsole.WriteLine(new decimal(0, 0, 1, false, 0)); //18446744073709551616\nConsole.WriteLine(new decimal(1, 0, 0, false, 1)); //0.1\nConsole.WriteLine(new decimal(1, 0, 0, true, 1)); //-0.1	0
30230930	30230832	c# lambda reading each row with GROUP BY and SUM	var topProducts = sellingLog\n       .Where(s => s.salesYear == 2014)\n       .GroupBy(u => u.productCode)\n       .Select(g => new { productCode = g.Key, sales = g.Sum(u => u.productSales) })\n       .OrderByDescending(x => x.productCode)\n       .Take(5)\n       .ToList();	0
5037098	5037062	Take a picture from Integrated Laptop Camera using C#	WIA.CommonDialog wiaDiag = new WIA.CommonDialog();	0
14523640	14502890	Getting wall brutto area in Revit API	doc.Delete(delIds);\ndoc.Regenerate();  // regenerate to cascade all changes.\nwallElem = doc.get_Element(wallElem.Id);\nbrutto = wallElem.get_Parameter(BuiltInParameter.HOST_AREA_COMPUTED).AsDouble();	0
18097217	17825294	How to read serial number of a Gemalto smart card?	SmartCard.Transport.PCSC.SelectDialog dialog = new SmartCard.Transport.PCSC.SelectDialog();\nCardAccessor ca = new CardAccessor(dialog.SelectedReader);\nif(ca.Logon())\n{\nca.GetSerialNumber();\n}	0
4379385	4379272	Serializing readonly member data	public string Name\n{\n  get {return _name;}\n  set { }\n}	0
3474557	3474531	LINQ and how to return a list of a specific type	var result = (from dc in _context.DocClasses\n             join d in _context.Documents\n             on dc.DocClassID equals d.DocClassID\n             where dc.DocClassID != 0 && docIds.Contains(d.DocID)\n             let children = from p in _context.DocClasses\n                            where dc.ParentID == p.DocClassID\n                            select new Child {\n                                              ChildId = dc.DocClassID,\n                                              ChildDocClassName = dc.DocClassName,\n                                              ParentId = p.DocClassID,\n                                              ParentDocClassName = p.DocClassName\n                                              }\n              select children).SelectMany(c=>c).ToList();	0
5903722	5833175	How to map a dictionary with a complex key type (CultureInfo) using FluentNHibernate	HasMany(n => n.LanguageValues)\n    .Access.ReadOnlyPropertyThroughCamelCaseField()\n    .AsMap<CultureInfo>("CultureName")\n    .Element("Phrase")\n    .Table("MultilingualPhraseValues");	0
9828639	9828586	How to make my Outlook 2007 add-in trusted	caspol -u -ag All_Code -url "{The assembly???s full path}" FullTrust -n "{The code group name}".	0
13435985	13433726	How can I open a page and assign its datacontext	public static UIELEMENT FindUiElementUpVisualTree(DependencyObject initial)\n    {\n        DependencyObject current = initial;\n\n        while (current != null && current.GetType() != typeof(UIELEMENT))\n        {\n            current = VisualTreeHelper.GetParent(current);\n        }\n        return current as UIELEMENT;\n    }	0
19877358	19876979	How to set up a complex many to many relationship in entity framework 4 code first	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n{\n    modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();\n    modelBuilder.Entity<Entity1>()\n        .HasMany(b => b.Entities2)\n        .WithMany(p => p.Entities1)\n        .Map(m =>\n        {\n            m.ToTable("Entitie1Entity2");\n            m.MapLeftKey("Entity1Id");\n            m.MapRightKey("Entity2Id");\n        });            \n    }	0
885091	868701	How to check if file is under source control in SharpSvn?	using(SvnClient client = new SvnClient())\n{\n    SvnStatusArgs sa = new SvnStatusArgs();\n    sa.Depth = SvnDepth.Empty; // Adjust this to check direct files, or (recursive) directories etc\n\n    Collection<SvnStatusEventArgs> statuses;\n    client.GetStatus("c:\\somefile.txt", sa, out statuses); \n\n    Assert.That(statuses.Count, Is.EqualTo(1));\n    Assert.That(SvnStatus.NotVersioned, Is.EqualTo(statuses[0].LocalContentStatus));\n}	0
31026760	31026651	How to sort the list order using Linq?	myList = myList.OrderByDescending(x => x.ProgramId)\n    .ThenBy(x => x.Level)\n    .ThenBy(x => x.Special);	0
11519853	11519770	Append-Method gives back a '-' instead of space if used as select-statement	sqlQuery.ToString()	0
18976935	18974031	How do I remove link annotations from a PDF using iText?	//Get the current page\nPageDictionary = R.GetPageN(i);\n\n//Get all of the annotations for the current page\nAnnots = PageDictionary.GetAsArray(PdfName.ANNOTS);\n\nforeach (PdfObject A in Annots.ArrayList)\n{\n//code to check the annotation \n\n//remove the annotation\nAnnots.Remove(int idx);\n\n}	0
7969822	7968776	How can I serialize a collection of SyndicationItem objects?	SyndicationItem item = new SyndicationItem("Item Title", "Item Content", new Uri("http://Item/Alternate/Link"), "itemID", DateTimeOffset.Now);\nXmlWriter writer = XmlWriter.Create("outfile.xml");\nitem.SaveAsRss20(writer);\nwriter.Close();	0
10483584	10482987	Automatically play next item in listbox	private int currentSongIndex = -1;\n\nvoid Player_MediaEnded(object sender, EventArgs e)\n{\n    if(currentSongIndex == -1)\n    {\n        currentSongIndex = listBox.SelectedIndex;\n    }\n    currentSongIndex++;\n    if(currentSongIndex < listBox.Items.Count)\n    {\n        player.Play(listBox.Items[currentSongIndex]);\n    }\n    else\n    {\n        // last song in listbox has been played\n    }\n}	0
17187142	17184715	How to manage global variables in Spec Flow	ScenarioContext.Current["KeyName"]	0
4161224	4161175	How do I get the count of attributes that an object has?	Type type = typeof(StaffRosterEntry);\nint attributeCount = 0;\nforeach(PropertyInfo property in type.GetProperties())\n{\n attributeCount += property.GetCustomAttributes(false).Length;\n}	0
18270384	18270289	How to disable download pop up in browser from c# .Net	Byte[] buffer = client.DownloadData(path);\n\n        if (buffer != null)\n        {\n            Response.ContentType = "application/pdf";\n            Response.AddHeader("content-length", buffer.Length.ToString());\n            Response.BinaryWrite(buffer);\n        }	0
5986462	5986194	Saving changes to an external config file specified in configSource attribute of custom section	Configuration c = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nc.AppSettings.Settings["Your config"].Value=....;\nc.Save(ConfigurationSaveMode.Modified);	0
25278727	25278109	how to set direction in cell of gridview	e.Row.Cells[11].Style.Add("dir", "rtl");	0
2379603	2379544	C# Interfaces with optional methods	interface ITest\n{\n    void MethodOne();\n}\n\ninterface ITest2 : ITest\n{\n    void MethodTwo();\n}	0
28358562	28357490	Binding for ComboBox Header in DataGrid	"{Binding DataContext.oTran, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}"	0
3313837	3310718	Tracking recently crashed applications	System.Diagnostics.EventLog	0
9116323	9115865	Is it possible to set height and width of image which was assigned to a label dynamically	lblPopup.Text = "<img src='Popup(Images)/notfound.png' />&nbsp;&nbsp;&nbsp;&nbsp; Access Denied,Contact Administrator";\nString strInsertStyle = " style=\"height: 100px; width: 100px;\"";\nint intInsertPoint = lblPopup.Text.IndexOf("<img") + 4;\nlblPopup.Text = lblPopup.Text.Substring(0, intInsertPoint) + strInsertStyle + lblPopup.Text.Substring(intInsertPoint);	0
1655601	1655584	C#, writing binary data	//This is preparing the counter as binary\nint nCounterIn = ...;\nint nCounterTotalInNetwork = System.Net.IPAddress.HostToNetworkOrder(nCounterIn);\nbyte[] byteFormat = BitConverter.GetBytes(nCounterTotalInNetwork);\nm_brWriter.Write(byteFormat);\nm_brWriter.Flush();	0
28304622	28303756	C# Serialization to XML using XmlWriter	xml.WriteStartDocument();\nxml.WriteStartElement("userProfiles");\nxml.WriteElementString("groupId", "1");\n\nforeach (var profile in profiles)\n{\n    xml.WriteStartElement("profile");\n    xml.WriteElementString("name", "test 1");\n    xml.WriteElementString("id", "10000");\n    xml.WriteStartElement("userPerformance");\n\n    xml.WriteElementString("type", "yearly");\n    // assume that I have the proper allDays as a List of DateTime\n    foreach (var days in allDays)\n    {\n        // What will be my StartElement?\n        xml.WriteStartElement("values");\n        xml.WriteElementString("start", DateTime.Now.ToString());\n        xml.WriteElementString("end", DateTime.Now.ToString());\n        xml.WriteElementString("value", "0815");\n        xml.WriteEndElement();\n    }\n    xml.WriteEndElement();\n    xml.WriteEndElement();\n}\n\nxml.WriteEndElement();	0
11545380	11545253	XNA - no definition for 'isMouseVisible'	IsMouseVisible = true	0
11631645	11618427	Update List<string> in mongoDB	List<string> Images = someList;\nvar update = Update.Set("Images", new BsonArray(Images));\ncollection.Update(query, update, UpdateFlags.Upsert);	0
17755216	17075544	Get all users based on Profile	var users = Membership.GetAllUsers();\n\nList<MembershipUser> searchResults = users.Where(user => Profile.GetProfile(user.UserName).CustomerID.ToLowerInvariant().Contains(CustomerID.ToLowerInvariant())).ToList();	0
337361	337327	NUnit test DateTime without .Net Timespan or DateTime function	DateTime a = DateTime.Now;\n      DateTime b = a.AddDays(2);\n\n      // ticks are in hns\n      long ticks = b.Ticks - a.Ticks;\n      long seconds = ticks / 10000000;\n      long minutes = seconds / 60;\n      long hours = minutes / 60;\n      long days = hours / 24;	0
5183491	5182629	iTextSharp first page text higher	using(MemoryStream PDFData = new MemoryStream())\n    using(Document document = new Document(PageSize.A4, 50, 50, 80, 50))\n    {\n        PdfWriter PDFWriter = PdfWriter.GetInstance(document, PDFData);\n\n        document.Open();\n\n        Moviecollection movCol = new Moviecollection();\n\n        foreach (Movie mov in movCol.Movies)\n            document.Add(new Paragraph(mov.Description));\n    }	0
2611008	2610929	ASP MVC2 model binding issue on POST with strongly-typed HTML helpers	public ActionResult Registration([Bind(Prefix = "data")] AccountViewInfo viewInfo);	0
32929292	32929211	How to convert a nested for each loop into Linq when the two lists are of different types	foreach (var presentedDocuments in innerdocuments)\n{\n    var doc = outerDocuments.FirstOrDefault(a => a.DocumentId.Equals(presentedDocuments.DocumentId));\n    if (doc != null)\n    {\n        presentedDocuments.IsValid = doc.IsValid;\n    }\n}	0
20413839	20398405	How to get range of last column excel (spreadsheetgear)	public static int findNullRow(DataTable dt)\n   {\n       int row = 0;\n\n       for (int a = 0; a < dt.Rows.Count; a++)\n       {\n           if (dt.Rows[a][0] == null)\n           {\n               row = a;\n               break;\n           }\n       }\n\n       return row;\n   }\n\n   public static int findNullColumn(DataTable dt)\n   {\n       int col = 0;\n\n       for (int i = 0; i < dt.Columns.Count; i++)\n       {\n           if (dt.Rows[0][i] == null)\n           {\n               col = i;\n               break;\n           }\n       }\n\n       return col;\n   }	0
17727943	17727655	How to break out of an if statement from a boolean inside the if statement	if(plot)\n{\n    if(a)\n    {\n        b= !b;\n        if( b )\n        {\n            //do something meaningful stuff here\n        }\n    }\n    //some more stuff here that needs to be executed\n}	0
12869884	12869820	How to change the contents of a form	private void button1_Click(object sender, EventArgs e)\n{\n    textBox1.Visible = false; // to hide textbox\n    button1.Size = new Size(60, 20);// for changing button layouts\n}	0
29536610	29521064	WriteProcessMemory - String length bug	public static bool WriteString(IntPtr handle, int address, string value)\n{\n    int written;\n\n    byte[] data = Encoding.Default.GetBytes(value + "\0");\n\n    return WriteProcessMemory(handle, address, data, data.Length, out written);\n}	0
19364219	19363628	Ctrl + C doesn't work correctly in a Windows Forms application	using System;\nusing System.Windows.Forms;\n\nclass MyDataGridView : DataGridView {\n    protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        if (keyData == (Keys.Control | Keys.C)) {\n            // Do stuff\n            //..\n            return true;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }\n}	0
16741621	16738664	C# deserialization element mapping	using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Runtime.Serialization;\n\nnamespace SandboxConoleApp\n{\n\n    internal class Program\n    { \n        private static void Main(string[] args)\n        {\n            DatabaseRestoreStatus data = null;\n            using (var stream = File.Open("test.xml",FileMode.Open))\n            {\n                var formatter = new DataContractSerializer(typeof(DatabaseRestoreStatus));\n                data = (DatabaseRestoreStatus)formatter.ReadObject(stream);\n            } \n        }\n    }\n\n    [DataContract(Name = "job-status", Namespace = "http://marklogic.com/xdmp/job-status")]\n    public class DatabaseRestoreStatus\n    {\n        [DataMember(Name = "forest")]\n        public Forest Forest { get; set; }\n    }\n\n    [DataContract(Name = "forest", Namespace = "http://marklogic.com/xdmp/job-status")]\n    public class Forest\n    {\n        [DataMember(Name = "status")]\n        public string Status { get; set; }\n    }\n}	0
15950388	15950142	C# remove part of string in Time	string time = "09:19:30.5070000 AM";\n\nStringBuilder sb = new StringBuilder(time);\nstring final = sb.Remove(8, 8).ToString();	0
18101228	18101033	Is there any premade function to help resize controls based on their parent control?	yourControl.Dock = DockStyle.Fill	0
28189283	28164297	How to apply ReliableSqlConnection's retry policy on SqlDataAdapter/DataSet	using(var sqlConnection = new ReliableSqlConnection(_connectionString, _connectionRetry, _commandRetry)\n{\n    var command = sqlConnection.CreateCommand();\n    command.CommandText = "...";\n    sqlConnection.Open();\n\n    var dataReader = sqlConnection.ExecuteCommand<SqlDataReader>();\n    var dataTable = new DataTable();\n    dataTable.Load(dataReader);\n\n    // handle dataTable, in our case the data set only returns one table, so it's ok\n    ...\n}	0
24368232	24368165	How do I deserialize a List<T> as another List<T> instead of a readonly T[]?	DataContractSerializer(typeof(List<ITestObject>)	0
6349925	6349698	Linq: select from multiple tables into one pre-defined entity	IEnumerable<A> result = (from a in A join b in B on a.id equals b.id_A\n                         group b by b.id_A into g\n                         select new\n                         {\n                             Name = a.name,\n                             Total = g.Sum(b => b.quantity)\n                         })\n                        .ToArray()\n                        .Select(item => new A\n                        {\n                            Name = item.Name,\n                            TotalQuantity = item.Total\n                        });	0
4260932	4260897	LINQ query to query a list with array members	private List<string> GetSearchResult(List<string> SourceList,string name, string[] items)\n{\n     return SourceList.Where(entry => entry.name == name && items.Contains(entry.id)).ToList();\n}	0
21600190	21600023	Rethrow an Exception with correct line numbers in the stack trace	[WebMethod]\npublic void ExceptionTest()\n{\n    try\n    {\n        throw new Exception("An Error Happened");\n    }\n    catch (Exception ex)\n    {\n        evlWebServiceLog.WriteEntry(ex.ToString(), EventLogEntryType.Error);\n        throw new Exception("Your message", ex);\n    }\n}	0
19391362	19391073	using Stream writer to Write a specific bytes to textfile	using (FileStream fsStream = new FileStream("Bytes.data", FileMode.Create))\nusing (BinaryWriter writer = new BinaryWriter(fsStream, Encoding.UTF8))\n{\n    // Writing the strings.\n    writer.Write("The");\n    writer.Write(" strings");\n    writer.Write(" I");\n    writer.Write(" want");\n    writer.Write(".");\n\n    // Writing your bytes afterwards.\n    writer.Write(new byte[]\n                 {\n                     0xff,\n                     0xfe\n                 });\n}	0
7422742	7422625	Right align currency in string format	string sym = CultureInfo.CurrentCulture.NumberFormat.CurrencySymbol;\n Console.WriteLine("{0}{1,10:#,##0.00}",sym, number1);\n Console.WriteLine("{0}{1,10:#,##0.00}",sym, number2);	0
9057917	9057478	Mono using MPAPI	(g)mcs -r:/path/to/MPAPI.dll Program.cs	0
5615340	5615249	Is it possible to programatically open a combobox on Form_Show, using mobile framework?	protected override void OnLoad(EventArgs e) {\n        base.OnLoad(e);\n        this.BeginInvoke(new Action(() => comboBox1.DroppedDown = true));\n    }	0
7153520	7153460	How do I reference a field in LINQ that is named using a reserved word?	UserType.Type	0
10591782	10591687	How can I return a JArray from a [WebMethod] using Json.NET?	[WebMethod]\npublic string GetJsonData()\n{\n    JArray jArray = new JArray();\n    JObject jObject = new JObject();\n    jObject.Add(new JProperty("name", "value"));\n    jArray.Add(jObject);\n    return jArray.ToString();\n}	0
11848217	11848122	Convert YYYYMMDD string to MM/DD/YYYY string	string res = "20120708";\nDateTime d = DateTime.ParseExact(res, "yyyyddMM", CultureInfo.InvariantCulture);\nConsole.WriteLine(d.ToString("MM/dd/yyyy"));	0
29278939	29278655	In C#, in a numerical textbox, how do I prevent a decimal point being placed in as the first digit only?	char decimalChar = Convert.ToChar(CultureInfo.CurrentCulture.NumberFormat.NumberDecimalSeparator);\n\n  if (!char.IsDigit(e.KeyChar) && e.KeyChar != (char)Keys.Back && e.KeyChar != decimalChar)\n  {\n    e.Handled = true;\n  }\n  else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.IndexOf(decimalChar) > -1))\n  {\n    e.Handled = true;\n  }\n  else if ((e.KeyChar == decimalChar) && ((sender as TextBox).Text.Length == 0))\n  {\n    e.Handled = true;\n  }	0
22831077	22221989	changing Datatype of DataTable using decimal	private static DataTable CompareTwoDataTable(DataTable table1, DataTable table2)\n\n       {\n\n        DataTable table3 = new DataTable();\n        DataRow dr = null;\n        string filterExp = string.Empty;\n        for (int i = 0; i < table1.Rows.Count; i++)\n        {\n\n            string col = table1.Rows[i]["Par Name"].ToString();\n            if (table2.Columns.Contains(col))\n            {\n                if (!table3.Columns.Contains(col))\n                {\n                    table3.Columns.Add(col, typeof(double));\n                    filterExp = filterExp + col + " asc ,";\n                }\n\n                for (int j = 0; j < table2.Rows.Count; j++)\n                {\n                    if (table3.Rows.Count != table2.Rows.Count)\n                    {\n                        dr = table3.NewRow();\n                        table3.Rows.Add(dr);\n                    }\n                    table3.Rows[j][col] = table2.Rows[j][col];\n                }\n\n\n            }\n\n\n        }	0
22492678	22491338	Write NameSpaces in XML	XNamespace ns1 = "http://localhost:8080/WsNFe2/lote";\nXNamespace tipos = "http://localhost:8080/WsNFe2/tp";\nXNamespace xsi = "http://www.w3.org/2001/XMLSchema-instance";\n\nvar doc = new XElement(ns1 + "ConsultaSeqRps",\n    new XAttribute(XNamespace.Xmlns + "ns1", ns1), \n    new XAttribute(XNamespace.Xmlns + "tipos", tipos), \n    new XAttribute(XNamespace.Xmlns + "xsi", xsi),\n    new XAttribute(xsi + "schemaLocation", \n      "http://localhost:8080/WsNFe2/lote http://localhost:8080/WsNFe2/xsd/ConsultaSeqRps.xsd")\n    );	0
22630061	22629840	How to create a class for session in mvc	public class Session : ISession {\n    private const string CURRENTUSERKEY = "CurrentUser";\n    public static string CurrentUser {\n        get { return (string)HttpContext.Current.Session[CURRENTUSERKEY]; }\n        set { HttpContext.Current.Session[CURRENTUSERKEY] = value; }\n    }\n\n    public static void ClearAllSession() {\n        CurrentUser = null; // And the other props\n    }\n}	0
5206336	5206326	How do you open a console application?	Process.Start(@"console_app.exe");	0
14783310	14783261	XML parsing: attributes instead of elements	.Select(y => y.Attributes()\n              .ToDictionary(x => x.Name, x => x.Value))	0
23880927	23880831	How to Make List of List	List<List<string>> myList = new List<List<string>>();\nmyList.Add(new List<string> { "a", "b" });\nmyList.Add(new List<string> { "c", "d", "e" });\nmyList.Add(new List<string> { "qwerty", "asdf", "zxcv" });\nmyList.Add(new List<string> { "a", "b" });\n\n// To iterate over it.\nforeach (List<string> subList in myList)\n{\n    foreach (string item in subList)\n    {\n        Console.WriteLine(item);\n    }\n}	0
24992974	24992816	XML Root Element Parsing	var doc = XDocument.Load(...);\nvar themeName = doc.Root.Element("themename").Value;\nGuid themeGuid = Guid.NewGuid();\nforeach (var element in doc.Root.Element("masterpages").Elements("masterpage"))\n{\n    ActiveTheme theme = new ActiveTheme\n    {\n        ThemeName = themeName,\n        ActiveThemeId = themeGuid,\n        Page = element.Attribute("page").Value,\n        MasterPage = element.Attribute("name").Value\n    };\n    portalContent.AddToActiveTheme(theme);\n}\nportalContext.SaveChanges();	0
12873724	12409529	Prevent closing a WinForms window?	private void Form1_FormClosing( object sender, FormClosingEventArgs e ) {\n            var window = MessageBox.Show( "Close the window", buttons: MessageBoxButtons.YesNo );\n            if (window == DialogResult.No) e.Cancel = true;\n            else e.Cancel = false;\n        }	0
22619060	21297066	Displaying an object's variable values that are not equal to 0	foreach (PropertyInfo prop in obj.GetType().GetProperties(\n    BindingFlags.Public | BindingFlags.Instance))\n{\n    if (prop.PropertyType != typeof(int)) continue;\n\n    int val = (int)prop.GetValue(obj);\n    if(val != 0) Console.WriteLine("{0}={1}", prop.Name, val);\n}	0
5419002	5382439	How to prevent application hang during permissions check using WMI	Task.Factory.StartNew(() =>\n  {\n    // Your permission checking code here.....\n  }).ContinueWith((t) =>\n  {\n    // Inform user of permissions status.\n  });	0
30476934	30476857	How to make TextBox handle text like a hyperterminal in c#?	private void keypressed(Object o, KeyPressEventArgs e)\n{\n    // The keypressed method uses the KeyChar property to check \n    // whether the ENTER key is pressed. \n\n    // If the ENTER key is pressed, the Handled property is set to true, \n    // to indicate the event is handled.\n    if (e.KeyChar == (char)Keys.Return)\n    {\n        e.Handled = true;\n    }\n}	0
29899731	29899557	Interfaces for Player Attributes	public interface IBaseUnit \n{\n     int HitPoints\n     ..\n}	0
14772461	14772245	Remove semicolons from list items	List<String> lst = new List<string>();\n        lst.Add("Life Skills");\n        lst.Add("Life Skills");\n        lst.Add("Communication");\n        lst.Add("Careers; Listening Skills;Life Skills; Personal Development; Questioning Skills; Coaching/Mentoring; Recognition; Recruitment and Selection.");\n        lst.Add("No Related Topics");\n\n        List<string> newList = new List<string>();\n\n        foreach (string str in lst)\n        {\n            var temp = str.Split(';');\n            if (temp.Length > 1)\n            {\n                for (int i = 0; i < temp.Length; i++)\n                {\n                    if (!newList.Contains(temp[i]))\n                    {\n                        newList.Add(temp[i]);\n                    }\n                }\n            }\n            else\n            {\n                if (!newList.Contains(str))\n                {\n                    newList.Add(str);\n                }\n            }\n        }	0
29091076	29091036	How do i make XML from a List?	var xEle = new XElement("t",\n                from ele in t\n                select new XElement("test1",\n                             new XElement("BINID", ele.ID),\n                               new XElement("NUMBER1", ele.Number1),\n                               new XElement("HOLOGRAPHIC", ele.Holigraphic)\n                           ));\n\n    xEle.Save("D:\\yourFile.xml");\n    Console.WriteLine("Converted to XML");	0
13832409	13831963	How to open the calendar of the datepicker from code behind?	private void departDate_SelectedDateChanged(object sender, SelectionChangedEventArgs e)\n{\n   returnDate.isDropDownOpen = true;\n}	0
27890580	27887585	Insert a specific id into auto incremented field in MySQL with Entity Framework 5	SET FOREIGN_KEY_CHECKS=0;\n\nALTER TABLE Profile DROP PRIMARY KEY,\nMODIFY _id INT PRIMARY KEY NOT NULL;\n\ninsert commmand here....\n\nALTER TABLE Profile DROP PRIMARY KEY,\nMODIFY _id INT AUTO_INCREMENT PRIMARY KEY NOT NULL;\n\nSET FOREIGN_KEY_CHECKS=1;	0
13064059	13031778	How can i extract a file from an embedded resource and save it to Disk?	private static void ExtractEmbeddedResource(string outputDir, string resourceLocation, List<string> files)\n    {\n        foreach (string file in files)\n        {\n            using (System.IO.Stream stream = System.Reflection.Assembly.GetExecutingAssembly().GetManifestResourceStream(resourceLocation + @"." + file))\n            {\n                using (System.IO.FileStream fileStream = new System.IO.FileStream(System.IO.Path.Combine(outputDir, file), System.IO.FileMode.Create))\n                {\n                    for (int i = 0; i < stream.Length; i++)\n                    {\n                        fileStream.WriteByte((byte)stream.ReadByte());\n                    }\n                    fileStream.Close();\n                }\n            }\n        }\n    }	0
9688143	9687981	Sorting Child Collection in Entity Framework While Building Dynamic Statement	TradesFilter =\n  SortDirection.Equals(SortDirection.Ascending) ?\n  TradesFilter.OrderBy(s => s.TradeLineItems.Min(t => TradeDateTime)) :\n  TradesFilter.OrderBy(s => s.TradeLineItems.Max(t => TradeDateTime));	0
22587924	22587824	Manipulate control properties inside panel	foreach(Control ctrl in myTextBoxContainer.Controls)\n        { \n            if(ctrl is TextBox)\n            {\n                TextBox textbx = ctrl as TextBox; \n                if(textbx.ReadOnly == false)\n                {\n                    textbx.ReadOnly = true; \n                }\n            }\n        }	0
10030720	10030681	Handlers of elements of WrapPanel	_b.Tap += yourHandler;	0
29216844	29216639	How can I take flat rows of relational data and put these into a C# class?	context.Questions\n.GroupJoin\n(\n    context.Answers,\n    x=>x.Id, // this is the pk on Questions\n    x=>x.QuestionId //this is the fk on Answers\n    (q,a)=>new Question\n    {\n        q.QuestionUId,\n        q.Text,\n        Answers = a.Select(an=>new Answer{an.AnswerId,an.AnswerText})\n    }    \n)	0
1162211	1162127	How to save contacts in an address book and list them?	Console.WriteLine("Here are a list of colors:");\n\nforeach(Color.clr item in Enum.GetValues(typeof(Color.clr)))\n{\n    Console.WriteLine(string.Format("{0} - {1}",(int)item,item.ToString()));\n}\nConsole.WriteLine("Please choose your color");\nstring colorInput = Console.ReadLine();\nint colorValue = 0;\nif(!int.TryParse(colorInput, out colorValue))\n{\n        Console.WriteLine(string.Format("{0} is not a valid number",colorInput));\n        return;\n}\n\n// This will give an error if they've typed a number that wasn't listed\n// So need to add a bit of checking here\nColor.clr tempColor = (Color.clr)colorValue;\n\n// Your code here	0
29877251	29876956	Convert 1000 months in 83 years and 4 months	int _campingDaysAdj = 30 - campingDays;\nif(_campingDaysAdj > 0 && pagesPerDay > 0)\n{\n    int months = page / ((30 - campingDays) * pagesPerDay);\n    int years = months / 12;\n    int remainingMonths = months % 12;\n\n    Console.WriteLine("{0} years {1} months", years, remainingMonths);\n}\nelse\n{\n    //throw an exception or an error message etc.\n}	0
24802380	24802109	How to pass a C# array to a JavaScript array	string json = JsonConvert.SerializeObject(array2D);	0
24333741	24143970	EWS Getting all occurences from a master recurrence appointment	appointment.recurrence	0
28813596	28812834	how to show this linq query in a label or textbox using c#?	Label.Text = re.Users.Single(u=> u.Name == struname).privilege;	0
32659083	32659026	How to check if a property of a class has thrown an exception	try/catch	0
24822219	24821649	Disable button on update progress in ASP.net Ajax	function clickOnLoadReport() {\n        var requestManager = Sys.WebForms.PageRequestManager.getInstance();\n        requestManager.add_initializeRequest(CancelPostbackForSubsequentSubmitClicks);\n\n        function CancelPostbackForSubsequentSubmitClicks(sender, args) {\n            if (requestManager.get_isInAsyncPostBack() &\n        args.get_postBackElement().id == 'BtnLoadReport') {\n                args.set_cancel(true);\n                document.getElementById("BtnLoadReport").setAttribute("disabled", "disabled");\n                //alert('A previous request is still in progress that was issued on clicking ' + args.get_postBackElement().id);\n            }\n        }\n    }	0
8268384	8268044	How to pick a single element from an embedded array with the official C# driver. Best practice?	// it will skip 0 elements and load only one element from nested array\n var slice = Fields.Slice("Participants", 0, 1);	0
15664079	15663899	Build a string of HEX and strings. How?	public class StringStuff\n{\n    private const char cr = '\x0d'; // segment terminator\n    private const char lf = '\x0a'; // data element separator\n    private const char rs = '\x1e'; // record separator\n    private const char sp = '\x20'; // white space\n\n    public string BuildString()\n    {\n        var a = "hello";\n        var b = "world";\n\n        var output = a + rs + b\n\n        return output;\n    }\n}	0
30602767	30600595	Is it possible to copy row (with data, merging, style) in Excel using Epplus?	for (int i = 0; i < invoiceList.Count; i++)\n    {\n        workSheet.Cells[1, 1, totalRows, totalCols].Copy(workSheet.Cells[i * totalRows + 1, 1]);\n    }	0
1732361	1731384	How to stop BackgroundWorker on Form's Closing event?	protected override void OnFormClosing(FormClosingEventArgs e) {\n    if (!mCompleted) {\n        backgroundWorker1.CancelAsync();\n        this.Enabled = false;\n        e.Cancel = true;\n        mClosePending = true;\n        return;\n    }\n    base.OnFormClosing(e);\n}\n\nvoid backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {\n    mCompleted = true;\n    if (mClosePending) this.Close();\n}	0
32320997	32320278	How properly to throttle access to DocumentDb from WebJobs	catch (AggregateException ex) when (ex.InnerException is DocumentClientException)\n{\n    DocumentClientException dce = (DocumentClientException)ex.InnerException;\n    switch ((int)dce.StatusCode)\n    {\n        case 429:\n            Thread.Sleep(dce.RetryAfter);\n            break;\n\n         default:\n             Console.WriteLine("  Failed: {0}", ex.InnerException.Message);\n             throw;\n     }                    \n}	0
24819788	24819627	How to get the Attribute name and the Elemnt value using XDocument	var dictionary = xdoc.Root.Elements("DataTable").Elements()\n               .ToDictionary(x => x.Name.LocalName, x => (string)x)	0
2571441	2571262	Storing entity in XML, using MVVM to read/write in WPF Application	var list = new List<Instance>();\n...\n\n// Serialization\n\nvar xs = new XmlSerializer(typeof(List<Instance>));\nusing (var writer = XmlWriter.Create(filename))\n{\n    xs.Serialize(writer, list);\n}\n\n...\n\n// Deserialization\n\nusing (var reader = XmlReader.Create(filename))\n{\n    list = xs.Deserialize(reader) as List<Instance>;\n}	0
14489837	14489799	How to write a custom POCO serializer/deserializer?	public string Serialize(object o)\n{\n    string result = ""; // TODO: use string builder\n\n    Type type = o.GeyType();\n\n    foreach (var pi in type.GetProperties())\n    {\n        string name = pi.Name;\n        string value = pi.GetValue(o, null).ToString();\n\n        object[] attrs = pi.GetCustomAttributes(true);\n        foreach (var attr in attrs)\n        {\n           var vp = attr as FIXValuePairAttribute;\n           if (vp != null) name = vp.Name;\n        }\n\n        result += name + "=" + value + ";";\n    }\n\n    return result;\n}	0
26554104	26553565	Use images instead of text in console application	System.Drawing	0
10376460	10376417	Read an undefined number of lines from standard input	List<int> input = new List<int>();\n\n// first read input till there are nonempty items, means they are not null and not ""\n// also add read item to list do not need to read it again    \nstring line;\nwhile ((line = Console.ReadLine()) != null && line != "") {\n     input.Add(int.Parse(line));\n}\n\n// there is no need to use ElementAt in C# lists, you can simply access them by \n// their index in O(1):\nStockItem[] stock = new StockItem[input.Count];\nfor (int i = 0; i < stock.Length; i++) {\n    stock[i] = new StockItem(input[i]);\n}	0
28640449	28636053	Creating SortedDictionary with LinkedList value	var UnitPriceIndex = new SortedDictionary<double, LinkedList<OrderItem>>();\n\nforeach (OrderItem item in Data)\n{\n    // Make sure the key exists. If it doesn't, add it \n    // along with a new LinkedList<OrderItem> as the value\n    if (!UnitPriceIndex.ContainsKey(item.UnitPrice))\n    {\n        UnitPriceIndex.Add(item.UnitPrice, new LinkedList<OrderItem>());\n    }\n\n    UnitPriceIndex[item.UnitPrice].AddLast(item);\n}	0
28667133	28667018	How to return from Inner function in c#?	public string WrapFunc(Dictionary<string, string> parameter)\n{\n    var response = "SUCCESS";\n    var missingParams = new List<string>();\n\n    //Check for required params\n    if (parameter.ContainsKey("Param1") && !string.IsNullOrEmpty(parameter["Param1"]))\n    {\n        objWebAPiRequest.Param1 = parameter["Param1"];\n    }\n    else\n    {\n        // Add the name of the missing param to a list\n        missingParams.Add("Param1");\n    }\n\n    if (missingParams.Any())\n    {\n        // Log all the missing parameters and set response to "FAILURE"\n        foreach (var p in missingParams)\n            LogRequiredParameterError(p);\n\n        response = "FAILURE";\n    }\n\n    return response;\n}\n\nprivate void LogRequiredParameterError(string parameterName)\n{\n    //Logging the missing parameter name to db\n}	0
5183945	5183929	Comparing Two Objects	Object.Equals()	0
9524707	9524681	LINQ - compare two lists	listA.Except(listB)	0
11430530	11430456	How to remove part of a string that contains within bracket in C#?	string x ="hello <!-- this is not meant to be here --> world, please help me";\n string y = Regex.Replace(x, "<!--.*?-->", "");	0
31605630	31602925	Screen Capture in PNG Format Works, but not BMP Format	png.Save(@"C:\Temp\MyFile.bmp", ImageFormat.Bmp)	0
27470506	27470496	Query a dictionary of hashsets	string searchFor = //\nbool allContain = dict.Values.All(s => s.Contains(searchFor));	0
22910404	22909417	Getting javascript text by RegEx C#	string value = Regex.Matches( inputString, @"\$\('#hotel'\)\.val\((\d+)\)", RegexOptions.None )[0].Groups[1].Value;	0
25157377	25156987	How to change json data in jquery	var data = [\n {  \n    data : 3, \n    Label : "Statement -2"\n }, \n { \n    data : 6, \n    Label : "this is a very long stat...s a very long statement"\n }]\n\nfor(var item in data){\n    data[item].data = [0,data[item].data]\n}	0
1083379	1083371	Executing excel from C# Application	startInfo.Arguments = @"C:\Users\un\Desktop\file with space"	0
16239679	16220309	Read CheckBox Values in ASP.Net from a SQL db?	while (reader.Read())\n{                    \nCheckBox1.Checked = (reader.GetBoolean(reader.GetOrdinal("Mount")));\nCheckBox2.Checked = (reader.GetBoolean(reader.GetOrdinal("Braker")));\nCheckBox3.Checked = (reader.GetBoolean(reader.GetOrdinal("Access")));\nCheckBox4.Checked = (reader.GetBoolean(reader.GetOrdinal("Conn_Net")));\nCheckBox5.Checked = (reader.GetBoolean(reader.GetOrdinal("Log_Book")));\nCheckBox6.Checked = (reader.GetBoolean(reader.GetOrdinal("Pictures")));\nCheckBox8.Checked = (reader.GetBoolean(reader.GetOrdinal("Floor")));\nCheckBox9.Checked = (reader.GetBoolean(reader.GetOrdinal("Cb_lenght")));\nCheckBox10.Checked = (reader.GetBoolean(reader.GetOrdinal("Channel")));\n}	0
12875327	12875301	Is there a way I can get a string value out of an enum in C#	string str =Enum.GetName(typeof(RoleType), obj);	0
28232669	28232466	C# datetime scope	string date = "20140231";\nDateTime result;\nint year = Convert.ToInt32(date.Substring(0, 4));\nint month = Convert.ToInt32(date.Substring(4, 2));\nint day = Convert.ToInt32(date.Substring(6, 2));\n\nresult = new DateTime(year, month, Math.Min(DateTime.DaysInMonth(year, month), day));	0
16137038	16136969	LINQ C# - Writing a query to display data in a pivot style	var pivot = Manufacturers.Select(m => new \n    { \n        Name = m.Name, \n        Products = Products\n            .Where(p => p.ManufacturerId == m.ManufacturerId)\n            .Select(p => p.Name)\n            .ToList()\n    });	0
1316317	1316312	How to format a DateTime variable to get the Month, and then put the value into a string in C#? [VS2005]	DateTime dt = Convert.ToDateTime(dateTimePicker1.Text); //taken the DateTime from form\nstring dt1 = dt.ToString("MMMM yyyy")	0
15497035	15496748	asp.net Button needs to be fired twice	protected override void LoadViewState(object state)\n{\n    base.LoadViewState(state);\n    var id = this.ViewState["DynamicControlGeneration"] as string;\n    if (id != null)\n        GenerateDynamicControls(id);\n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    string id = TextBox1.Text;\n    this.ViewState["DynamicControlGeneration"] = id;\n    GenerateDynamicControls(id);\n}	0
7570507	7570409	How to Extract current date, parse it and add 7 days	DateTime inSevenDays = DateTime.Today.AddDays(7);	0
25498034	25498002	How to manage DbContext in EF 6	public ActionResult DoSomething()\n{\n    using (GYOSContext context = new GYOSContext())\n    {\n        // Do stuff with context\n\n    }  // Automatically disposed when exiting scope of using block\n}	0
16051509	16050888	Finding classes in a DLL that inherit from classes in an unavailable assembly	using Mono.Cecil;\nusing Mono.Cecil.Cil;\n\nvar assembly = AssemblyDefinition.ReadAssembly("ClassLibrary.dll");\n// skip the first type '<Module>' whatever that is.\nvar types = assembly.MainModule.Types.Skip(1);\n\nforeach (var type in types)\n{\n    var interfaces = type.Interfaces.Select(i => i.FullName);\n    if (interfaces.Any())\n    {\n         Console.WriteLine("{0} : {1}, {2}", type.FullName, type.BaseType.FullName, string.Join(", ", interfaces));\n    }\n    else\n    {\n         Console.WriteLine("{0} : {1}", type.FullName, type.BaseType.FullName);\n    }\n}	0
25074907	25073731	How to change WP c4fToolkit:TimeSpanPicker value format	ValueStringFormat="{}{0:mm:ss}"	0
17479602	17479483	adding each line in a text file into a list c#	sting yourtextfile;\n//make all the different sections the same\nyourtextfile.replace("#main", "#");\nyourtextfile.replace("#extra", "#");\nyourtextfile.replace("!side", "#");\n//make all the arrays\nstring[] all = yourtextfile.Split('#');\nstring[] main = all[0].Split('\n');\nstring[] extra = all[1].Split('\n');\nstring[] side = all[2].Split('\n');	0
15787882	15787510	Accessing Ninject objects from master view partial view	IUnitOfWork UnitOfWork;\n\n    public AccountController(IUnitOfWork unitOfWork)\n    {\n        this.UnitOfWork = unitOfWork;\n    }	0
34128199	34116476	How to know if a point intersects a 3D object in a SolidWorks generated CAD file?	Solid3D.IsPointInside()	0
28183276	28183230	Reading and iterating through xml elements in C#	XDocument xdoc = XDocument.Load("myXmlFile.xml");\n\nvar servers = xdoc.Descendants("server"); \nfor (var server in servers) \n{\n    var children = server.Elements(); \n    for (var child in children)\n    {\n        // Do what you want with the server and child here\n    }\n}	0
24125722	24109145	Encapsulating ListBox in public property	public List<string>  GivenPermission\n    {\n        get { return lstGivenPermissions.Items.Cast<string>().ToList(); }\n        set { lstGivenPermissions.DataSource = value; }\n    }	0
10797349	10777524	nhibernate webApp serializing fluently configurated object	using(var file = File.Open(SerializedConfiguration, FileMode.Create))\n{\n    var bf = new BinaryFormatter();\n    bf.Serialize(file, configuration);\n}	0
29043739	29029684	Add direction to sphere without adding force	void OnCollisionEnter(Collision collision)\n{\nforeach (ContactPoint contact in collision.contacts) \n{\n    if(contact.thisCollider == collider1)\n    {\n        float cp = contact.point.x - transform.position.x;\n        contact.otherCollider.attachedRigidbody.AddForce(reflectionForce * cp, 0.0f, 0.0f);\n        float maxSpeed = 2.0f; //for example\n        Vector3 vel = contact.otherCollider.attachRigidbody.velocity;\n        contact.otherCollider.attachRigidbody.velocity = Vector3.ClampMagnitude(vel,maxSpeed);\n    }\n}	0
12662362	12648318	Handle Swipe Up, Swipe Down, Swipe Left & Swipe Right Gestures in a WinRT app	private Point initialpoint;\n\n    private void Grid_ManipulationStarted_1(object sender, ManipulationStartedRoutedEventArgs e)\n    {\n        initialpoint = e.Position;\n    }\n\n    private void Grid_ManipulationDelta_1(object sender, ManipulationDeltaRoutedEventArgs e)\n    {\n        if (e.IsInertial)\n        {\n            Point currentpoint = e.Position;\n            if (currentpoint.X - initialpoint.X >= 500)//500 is the threshold value, where you want to trigger the swipe right event\n            {\n                System.Diagnostics.Debug.WriteLine("Swipe Right");\n                e.Complete();\n            }\n        }\n    }	0
3775505	3775482	Access output from java compiler in C#	Process.StandardError	0
25241103	25240983	Unit test with Dependency Injection using struture map	var mockClientData = new Mock<IClientData>();\n\nmockClientData.SetupGet(data => data.MyProperty).Returns(3);\n// mockClientData.Object.MyProperty now returns 3\n\nmockClientData.Setup(data => data.MyMethod()).Returns(42);\n// mockClientData.Object.MyMethod() now returns 42\n// any other setup that you need done goes here\n\nvar controller = new HomeController(mockClientData.Object);\n\n// the rest of your test as normal	0
1778622	1778600	listview Header check-box	listview.OwnerDraw = true\n\n\n    private void listView1_DrawColumnHeader(object sender, DrawListViewColumnHeaderEventArgs e)\n    {\n        // Draw your custom checkbox control here\n    }\n\n    private void listView1_DrawItem(object sender, DrawListViewItemEventArgs e)\n    {\n        e.DrawDefault = true;\n    }\n\n    private void listView1_DrawSubItem(object sender, DrawListViewSubItemEventArgs e)\n    {\n        e.DrawDefault = true;\n    }	0
27950379	27950106	how to read output of a command run using cmd.exe	p.StartInfo.FileName = "sc.exe";\np.StartInfo.Arguments = "query eventlog";	0
1031461	1027910	Winforms: Screen Location of Caret Position	[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool GetCaretPos(out Point lpPoint);	0
12263725	12263644	if statement with no result in C# VS 2012	try\n    {\n        if (Properties.Settings.Default["Database"] != null)\n        {\n            MessageBox.Show("We landed on spot 1");\n        }\n        else\n        {\n            MessageBox.Show("We landed on spot 2");\n        }\n    }\n    catch (Exception ee)\n    {\n        MessageBox.Show(ee.Message);\n    }	0
781931	781905	Getting a list of logical drives	System.IO.DriveInfo.GetDrives()	0
8588607	628427	How to extend arrays in C#	string[] items = new string[3] { "input1", "input2", "input3" };\nstring[] furtherItems = new string[10];\n\n// array to list\nList<string> itemsList = items.ToList<string>();\n\nitemsList.Add("newItem");\n// or merge an other array to the list\nitemsList.AddRange(furtherItems);\n\n// list to array\nstring[] newArray = itemsList.ToArray();	0
22871119	22870756	Saving a generated file to the server	var doc = new Document();\nMemoryStream memoryStream = new MemoryStream();\nPdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);\n\ndoc.Open();\ndoc.Add(new Paragraph("First Paragraph"));\ndoc.Add(new Paragraph("Second Paragraph"));\n\nwriter.CloseStream = false;\ndoc.Close();\nmemoryStream.Position = 0;\n\nMailMessage mm = new MailMessage("username@gmail.com", "username@gmail.com")\n{\n    Subject = "subject",\n    IsBodyHtml = true,\n    Body = "body"\n};\n\nmm.Attachments.Add(new Attachment(memoryStream, "filename.pdf"));\nSmtpClient smtp = new SmtpClient\n{\n    Host = "smtp.gmail.com",\n    Port = 587,\n    EnableSsl = true,\n    Credentials = new NetworkCredential("username@gmail.com", "password")\n};\n\nsmtp.Send(mm);	0
21608861	21605795	Invert Colormap in ILNumerics	private void ilPanel1_Load(object sender, EventArgs e) {\n    ILArray<float> A = ILSpecialData.sincf(40, 50);\n    ilPanel1.Scene.Add(new ILPlotCube(twoDMode: false) {\n        new ILSurface(A) { new ILColorbar() }\n    });\n\n    // fetch surface\n    var surface = ilPanel1.Scene.First<ILSurface>();\n    // fetch current colormap data\n    ILArray<float> cmdata = surface.Colormap.Data;\n    // invert their positions\n    cmdata[":;0"] = cmdata["end:-1:0;:"];\n    // make new colormap and assign\n    surface.Colormap = new ILColormap(cmdata);\n    // configure after all modifications\n    surface.Configure();\n}	0
1735467	1735439	Switch Statement with Strings C#	namespace Simtho\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            foreach (string arg in Environment.GetCommandLineArgs())\n            {\n                switch (arg)\n                {\n\n                    case "-i":\n                        Console.WriteLine("Command Executed Successfully");\n                        Console.Read();\n                        break;\n                }\n            }\n        }\n    }\n}	0
31328128	31327827	How to set field during runtime	....\n    ....\n    if(membersName.Any(x => x == "Text"))\n    {\n        PropertyInfo propInfo = type.GetProperty("Text");\n        propInfo.SetValue(obj, ass.Text, null);\n    }\n    ....\n    ....	0
19573146	19573046	Service not showing in ServiceController but showing in Services and Registry table	var netTcpActivatorService = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "NetTcpActivator");\n\nvar netPipeActivatorService = ServiceController.GetServices().FirstOrDefault(s => s.ServiceName == "NetPipeActivator");	0
9901002	9894944	Ways of displaying exe icons in a ListView	private void Form_Load(object sender, EventArgs e)\n{\n    DirectoryInfo dir = new DirectoryInfo(@"c:\pic");\n    foreach (FileInfo file in dir.GetFiles())\n    {\n        try\n        {\n            this.imageList1.Images.Add(Image.FromFile(file.FullName));\n        }\n        catch\n        {\n            Console.WriteLine("This is not an image file");\n        }\n    }\n    this.listView1.View = View.LargeIcon;\n    this.imageList1.ImageSize = new Size(32, 32);\n    this.listView1.LargeImageList = this.imageList1;\n    //or\n    //this.listView1.View = View.SmallIcon;\n    //this.listView1.SmallImageList = this.imageList1;\n\n    for (int j = 0; j < this.imageList1.Images.Count; j++)\n    {\n        ListViewItem item = new ListViewItem();\n        item.ImageIndex = j;\n        this.listView1.Items.Add(item);\n    }\n}	0
7307791	7307753	SqlBulkLoad - loading xml to SQL	sourcedata = ds.Tables["Uploads"];	0
24310358	24310282	Breaking out of a 'for' loop from a ''case" statement	for {\nswitch(...) {\n        ....\n        goto MyLabel;\n    }\n}\nMyLabel:	0
3962468	3962448	Finding the shape created by two other intersecting shapes	Region::Intersect	0
619859	619856	Interface defining a constructor signature?	public class Foo : IParameterlessConstructor\n{\n    public Foo() // As per the interface\n    {\n    }\n}\n\npublic class Bar : Foo\n{\n    // Yikes! We now don't have a parameterless constructor...\n    public Bar(int x)\n    {\n    }\n}	0
9376601	9375781	Create function GetAllChechedBox with text and value and insert in new DataTable	public DataTable GetAllChechedBox()\n        {\n            var dt = new DataTable();\n                    dt.Columns.Add("Name");\n                    dt.Columns.Add("Value");\n            for (int i = 0; i < chkList.Items.Count; i++)\n            {\n                if (chkList.Items[i].Checked)\n                {\n                  dt.Rows.Add();\n                   dt.Rows[dt.Rows.Count-1]["Name"] = chkList.Items[i].Value;\n                    dt.Rows[dt.Rows.Count-1]["Value"] = chkList.Items[i].Text;\n\n                }\n            }\n        return dt;\n    }	0
13198160	13197935	Calling Method of subclass over interface without implementing the method there	public interface IPet\n{\n\n}\n\npublic interface IDog : IPet\n{\n    void Bark();    \n}\n\npublic class Dog : IDog\n{\n    public void Bark()\n    {\n        Console.WriteLine("Wouff!");    \n    }\n}	0
32588030	32587318	Can you access the gradient colour created in XAML in c# wpf	this.Label1.Background = (LinearGradientBrush)this.FindResource("headerBackground")	0
3753468	3753453	Cutting a part of path	var result = Path.Combine(Path.GetDirectoryName(@"C:\ol\il\ek"), @"ek\mek\gr");\n\n//  result == @"C:\ol\il\ek\mek\gr"	0
16432166	16432099	Using Escape Button to exit jquery popup dialog	keyup(function(e) {\n   if(e.keyCode == 27) {\n      // close your window\n   }\n});	0
11940676	11940537	Umbraco - Finding Root Node in C#	var rootNode = new Node(-1);	0
31195020	31178359	Has IBsonSerializationOptions been removed from the latest C# driver of MongoDB?	public class LocalDateTimeConvention : IMemberMapConvention\n{\n    public string Name\n    {\n        get { return "LocalDateTime"; }\n    }\n\n    public void Apply(BsonMemberMap memberMap)\n    {\n        if (memberMap.MemberType == typeof(DateTime))\n        {\n            var dateTimeSerializer = new DateTimeSerializer(DateTimeKind.Local);\n            memberMap.SetSerializer(dateTimeSerializer);\n        }\n        else if (memberMap.MemberType == typeof(DateTime?))\n        {\n            var dateTimeSerializer = new DateTimeSerializer(DateTimeKind.Local);\n            var nullableDateTimeSerializer = new NullableSerializer<DateTime>(dateTimeSerializer);\n            memberMap.SetSerializer(nullableDateTimeSerializer);\n        }\n    }\n}	0
1637799	1637780	Cast Dictionary KeyCollection to String array	String.Join(",", myDic.Keys.Select(o=>o.ToString()).ToArray());	0
4421035	4419001	Prevent C# from encoding brackets in query string	new Uri("http://example.com/name2id?names[]=john", true)	0
31173675	31173412	Stream reader.Read number of character	using (FileStream fileStream = new FileStream(path, FileMode.Open))\n        {\n            byte[] chunk = new byte[4];\n            fileStream.Read(chunk, 0, 4);\n            string hexLetters = BitConverter.ToString(chunk); // 4 Hex Letters that i need!\n        }	0
26934568	26934498	Get from .dll executors assembly	Assembly.GetEntryAssembly()	0
22954651	22954559	How to create alias of System Constants class	using Sc = MyNamespace.SystemConstants;	0
20800986	20800689	concept on looping on grid view row	bool isError=false;\nforeach (GridViewRow row in grdCart.Rows)\n    {\n\n        Response.Write("1");\n        var Qty = row.FindControl("lblQty") as Label;\n        var RemainQty = row.FindControl("lblremainqty") as Label;\n        var errormsg = row.FindControl("lblError") as Label;\n\n        if (Convert.ToInt32(Qty.Text) > Convert.ToInt32(RemainQty.Text))\n        {\n            errormsg.Text = "Stock Remain " + RemainQty.Text;\n            isError = true;\n            btnCheckOut.Enabled = false;\n        }\n        else\n        {\n            errormsg.Text = "";\n\n\n        }\n\n    }\nif(!isError)\n{\n  btnCheckOut.Enabled = true;\n}	0
12602206	12601966	Suitable use of BlockingCollection	private readonly CancellationTokenSource cts = new CancellationTokenSource();\n\n  public void Start()\n  {\n     blockingCollection= new BlockingCollection<int>();\n     var task = Task.Factory.StartNew(ProcessData, cts.Token);\n  }\n\n  private void ProcessData()\n  {\n    foreach(var item in blockingCollection.GetConsumingEnumerable(cts.Token))\n    {  \n        cts.Token.ThrowIfCancellationRequested();\n\n        // ...\n    }\n  }\n\n  public void Cancel()\n  {\n      cts.Cancel();\n  }	0
21574367	21574155	First occurrence of regular expression	^([aA]\s*\))(.*)([bB]\s*\))(.*)([cC]\s*\))(.*)	0
1501233	1501230	Unhashing a hash C#	initial  = Hash(password);\npossible = Hash("test");\n\nif( initial == possible ){\n    // we infer that password = "test"\n}	0
28529821	28524797	Windows Phone 8.1 Connect to Pebble via Bluetooth Rfcomm	00000000-deca-fade-deca-deafdecacaff	0
26827807	26827693	How to init an array of contours using memstorage	Contour<Point>[] control_shapes = Enumerable.Range(0, 13).Select(i => new Contour<Point>(new MemStorage())).ToArray();	0
5831936	5831498	Moving a time taking process away from my asp.net application	ThreadPool.QueueUserWorkItem()	0
23898749	23898680	In a DataTable object, how do I store an array of strings in each cell of a specific column?	var tasks = new[] {"Boss", "Secretary", "Tea Lady"};\n\nvar joined = string.Join(", ", tasks);\n\nvar splitAgain = joined.Split(new[]{", "}, StringSplitOptions.RemoveEmptyEntries);	0
16579729	16579664	Getting data from multiple tables with MysqlReader	string Query="SELECT Teams.Name as TeamName,Locations.Name as LocationsName,Address ,Address FROM `Teams`,`Locations` WHERE Teams.LocationId=Locations.LocationId;";\nOpenConnection();\nMySqlCommand MysqlCommand=new MySqlCommand(Query,MysqlConnection);\nMysqlReader=MysqlCommand.ExecuteReader();\nwhile (MysqlReader.Read()) {\n  ...\n  Team.Size=MysqlReader["Size"].ToString();\n  Location.Address=MysqlReader["Address"].ToString();\n  Team.Name=MysqlReader["TeamName"].ToString();\n  Location.Name=MysqlReader["LocationsName "].ToString();\n  ...\n}	0
18869973	18869838	Android Xamarin - Variable initiation asks method name	Button[] c = new Button[255]; // Initialise an array of buttons, length 255.\nc[0] = new Button(this); // Add a new button to index 0 of the array.	0
9947585	9947380	how to load data from XML file directly, instead of creating XML file by tring builder	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(@"E:\abcd\source.xml");\n\nstring data = xmlDoc.OuterXml;	0
11094841	11093321	How to create file kind entry on Google Doc by protocol?	?convert=false	0
12532091	12530918	How do you bind Icons to context menu defined in the resources	{Binding DataContext.ContextDeleteIcon, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type DataGrid}}}	0
33133923	33133157	How to build Npgsql?	dnu build	0
24351075	24350659	How to convert JSON Array to List<>?	attender = jUser["attendance"].ToObject<List<Attendance>>();	0
18133135	18131832	Using BeginExecuteNonQuery with async tasks	Task.Factory.FromAsync	0
29407577	29407388	Click element by textvalue with Page Object	FindsBy(How = How.XPath, Using = "//span[.='FASTPRIS']")	0
26745836	26745198	Use PTVS in VS2013 shell for own application	__init__.py	0
940064	940040	How do I use a transaction in LINQ to SQL using stored procedures?	using (var transaction = new TransactionScope())\n {\n     // do stuff here...\n     transaction.Complete();\n }	0
15369958	15369694	How PHP sentence looks on C#	string result = data + prop;	0
6004847	6004792	How can I center a ComboBox's content vertically?	VerticalContentAlignment="Center"	0
17405823	17271351	Enable/Disable all controls at client side on checkbox click in MVC 3	control1....\n\n control2....\n\n</div>	0
31986990	31986816	Rfc2898DeriveBytes password matches with string and not with byte[]	byte[] pass1 = new HashPassword("abc").ToArray();\nbyte[] pass2 = new HashPassword("abc").ToArray();	0
20202468	19929543	c# - How to pass the data from grid view to report Viewer?	ReportDataSource Rds = new ReportDataSource("DataSetName", GridView.DataSourceObject);	0
8645875	8645432	Posting data in Tab based page by partialview	[HttpPost]	0
16834833	16834739	Add box to picture C#	DrawingSurface.FillRectangle(new SolidBrush(Colors.Black), new Rectangle(0, height - 100, width, height));	0
7284629	7284563	How to download file from website url using SSIS package	System.Net.WebClient	0
11231238	11230774	Required field validator for date picker	TextBox.ValidationGroup = 1\nSubmit.ValidationGroup = 1\nrequiredFieldValidator.ValidationGroup = 1\nLinkButton.ValidationGroup = 2	0
3194501	3193746	set XmlDataProvider source without saving file	var xmlDocument = new XmlDocument();\nusing (var xmlReader = xDocument.CreateReader())\n{\n    xmlDocument.Load(xmlReader);\n}\nlistdataxml.Document = xmlDocument;	0
1328301	1327108	Internal C# "database" for keeping track of data	Dictionary<GUID, iTrackedClass>	0
30332386	30332204	Async EF 6 vs wrapped Sync EF	Task.Run	0
4780618	4780052	C# code equivalent for Applying RowValidationRules on DataGrid in WPF	grid.RowValidationRules.Add(new CourseValidationRule() { \n                ValidationStep = ValidationStep.UpdatedValue \n            });	0
29124194	29123934	How to loop through the selected values in a dataGridView?	foreach (var row in dataGridView.SelectedRows)\n{\n    // code here...\n}	0
32806427	32783877	Strange behavior of multiple call of Application.Run in Windows 10 environment	Thread thread1 = new Thread(() =>\n{\n    Application.Run(new Form1());\n});\nthread1.SetApartmentState(ApartmentState.STA);\nthread1.Start();\nthread1.Join();\n\nThread thread2 = new Thread(() =>\n{\n    Application.Run(new Form2());\n});\nthread2.SetApartmentState(ApartmentState.STA);\nthread2.Start();\nthread2.Join();	0
6458419	6458027	cant get c# to make a downloadable csv	ScriptManager sm = ScriptManager.GetCurrent(Page);\n        if (sm != null)\n            sm.RegisterPostBackControl(btnDownload); \n        //btnDownload = the button ID, just copied from your code.	0
892080	891958	Embedding a binary file inside a class library	byte[] theFile = myNamespace.Properties.Resources.theBinaryFile;	0
10826286	10826260	Is there a way to read from a website, one line at a time?	using System.IO;\nusing System.Net;\n\nvar url ="http://thebnet.x10.mx/HWID/BaseHWID/AlloweHwids.txt";\nvar client = new WebClient();\nusing (var stream = client.OpenRead(url))\nusing (var reader = new StreamReader(stream))\n{\n    string line;\n    while ((line = reader.ReadLine()) != null)\n    {\n        // do stuff\n    }\n}	0
24876293	24876046	In C#, how do I serialize my derived object to this XML?	[XmlRoot("CONTACT")]\n[XmlInclude(typeof(CR.Models.XactAnalysis.Phone))]\n[XmlInclude(typeof(CR.Models.XactAnalysis.Email))]\npublic class Contact\n{\n    [XmlArray("CONTACTMETHODS")]\n    public List<ContactMethod> ContactMethods { get; set; }\n}\n\npublic class ContactMethod\n{\n    [XmlElement("PHONE")]\n    public Phone Phone { get; set; }\n\n    [XmlElement("EMAIL")]\n    public Email Email { get; set; }\n}\n\n[XmlRoot("PHONE")]\npublic class Phone\n{\n    [XmlAttribute("number")]\n    public string Number { get; set; }\n}\n\n[XmlRoot("EMAIL")]\npublic class Email\n{\n    [XmlAttribute("address")]\n    public string Address { get; set; }\n}	0
10618365	10618041	Handling windows notifications in derived C# user control	using System;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nclass ExtendedTreeView : TreeView {\n    protected override void WndProc(ref Message m) {\n        if (m.Msg == WM_REFLECT + WM_NOFITY) {\n            var notify = (NMHDR)Marshal.PtrToStructure(m.LParam, typeof(NMHDR));\n            if (notify.code == NM_CLICK) {\n                MessageBox.Show("yada");\n                m.Result = (IntPtr)1;\n                return;\n            }\n\n        }\n        base.WndProc(ref m);\n    }\n    private const int NM_FIRST = 0;\n    private const int NM_CLICK = NM_FIRST - 2;\n    private const int WM_REFLECT = 0x2000;\n    private const int WM_NOFITY = 0x004e;\n\n    [StructLayout(LayoutKind.Sequential)]\n    private struct NMHDR {\n        public IntPtr hwndFrom;\n        public IntPtr idFrom;\n        public int code;\n    }\n}	0
13672594	13671993	How to convert from rectangular to polar form using C# Complex	static void Main(string[] args)\n    {\n        Complex RA = new Complex(25, 20);\n        Console.WriteLine("{0} + i{1}", RA.Real, RA.Imaginary);\n\n        double r, q, z;\n        r = Math.Sqrt((RA.Real * RA.Real) + (RA.Imaginary * RA.Imaginary));\n        q = Math.Atan(RA.Imaginary/RA.Real);\n        z = (q * (180/Math.PI));\n        Console.WriteLine("{0} < {1}", r, z);\n        Console.ReadLine();\n    }	0
3000326	3000251	How to create chronological Folder using c#?	public static DirectoryInfo GetCreateMyFolder(string baseFolder)\n    {\n        var now = DateTime.Now;\n        var yearName = now.ToString("yyyy");\n        var monthName = now.ToString("MMMM");\n        var dayName = now.ToString("dd-MM-yyyy");\n\n        var folder = Path.Combine(baseFolder,\n                       Path.Combine(yearName,\n                         Path.Combine(monthName,\n                           dayName)));\n\n        return Directory.CreateDirectory(folder);\n    }	0
23082488	23020185	Create SPListItem from ZipArchiveEntry without FileStream	public void ExtractLibraryZipFolder(SPWeb web, SPList myList, string FolderPath, SPFile myFile, bool overWrite)\n    {\n        ZipArchive myZip = new ZipArchive(myFile.OpenBinaryStream());\n\n        foreach (ZipArchiveEntry subZip in myZip.Entries)\n        {\n            MemoryStream myMemoryStream = new MemoryStream();\n            subZip.Open().CopyTo(myMemoryStream);\n            if (FolderPath != string.Empty)\n            {\n                SPFolder theFolder = web.GetFolder("/ImportToolLibrary/");\n                theFolder.SubFolders[FolderPath].Files.Add(subZip.Name, myMemoryStream);\n            }\n            else\n            {\n                SPFile myUpload = myList.RootFolder.Files.Add(subZip.Name, myMemoryStream);\n            }                \n        }\n    }	0
22943902	22943673	Array method Random number display	Random r = new Random();\n        int[] num = Enumerable.Range(0, 100).Select(x => r.Next(-100, 101)).ToArray();\n        double avg = num.Where(n => n < 0).Average();	0
10525262	10525148	C#, How to Consistantly bring a form to the front?	DialogResult dr = MyInput.ShowDialog(this);\n//test for result here\n\nMyInput.Close();	0
32905299	32905157	Go to marker when click on Button	// change the latlng to your specified latlng\n CameraUpdate camera = CameraUpdateFactory.NewLatLngZoom(latlng,10 );\n mMap.MoveCamera (camera);	0
12289567	12180976	Postback after clicking a button does not react not for the first time in a UserControl	private void LoadPage(string APageName)\n{\n    FAddress = null;\n    PlaceholderAddressTemplate.Controls.Clear();\n\n    if (!string.IsNullOrEmpty(APageName))\n    {\n        FAddress = (UserControl)LoadControl(string.Format("~/UserControls/{0}.ascx",\n                    APageName));\n\n        if (FAddress != null)\n        {\n            FAddress.ID = "UserControl1";\n\n            PlaceholderAddressTemplate.Controls.Add(FAddress);\n            ShowOrHideComponents();\n            FAddress.Focus();\n        }\n        else\n            ShowOrHideComponents();\n    }\n    else\n    ShowOrHideComponents();\n}	0
30898065	30897919	Linq implementation of for and if loop	foreach (var item in from l in list1\n                     where l == eCode\n                     select l)\n{\n    // Do something with each item\n}	0
17367534	17366978	Convert special characters to normal	var result = "Hello??".Unidecode();\nConsole.WriteLine(result) // Prints Helloae	0
13722438	12549854	Windows 8 Live Tile Background Agent Using C#	void OnCompleted(BackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs args)\n    { \n      var tile = CreateNotification(String.Format(@"<tile>\n      <visual>\n        <binding template=""TileSquareText04"">\n          <text id=""1"">{0}</text>\n          <text id=""2""></text>\n        </binding> \n        <binding template=""TileSquareText02"">\n          <text id=""1"">{0}</text>\n          <text id=""2""></text>\n        </binding>  \n      </visual>\n    </tile>", DateTime.Now.ToString("hh:mm:ss")));\n     TileUpdateManager.CreateTileUpdaterForApplication().Update(tile);\n     }\n    private TileNotification CreateNotification(string xml)\n    {\n        var xmlDocument = new XmlDocument();\n        xmlDocument.LoadXml(xml);\n        return new TileNotification(xmlDocument);\n    }	0
13611371	13611278	How to remove \r \n and other escape sequences in a string	keyRight = keyRight.Replace("\r\n", "");	0
27140561	27139091	Custom Control won't fill dock correctly	AutoSize = True\n    AutoSizeMode = GrowAndStrink	0
30805208	30804184	Find a windows control using partial NameProperty in windows automation	foreach(AutomationElement child in epoWindow.FindAll(TreeScope.Subtree, Condition.TrueCondition))\n  {\n      if (child.Current.Name.Contains("whatever"))\n      {\n          // do something\n      }\n  }	0
591491	590864	How do I set the Font color of a label to the same as the caption color of a GroupBox?	using System.Windows.Forms.VisualStyles;\n...\n\n    public Form1()\n    {\n      InitializeComponent();\n      if (Application.RenderWithVisualStyles)\n      {\n        VisualStyleRenderer rndr = new VisualStyleRenderer(VisualStyleElement.Button.GroupBox.Normal);\n        Color c = rndr.GetColor(ColorProperty.TextColor);\n        label1.ForeColor = c;\n      }\n    }	0
24302608	24302245	Shuffle the items based on order	var listOfStrings = new List<string>\n{\n    "Orange",\n    "Orange",\n    "Orange",\n    "Orange",\n    "Mango",\n    "Mango",\n    "Mango",\n    "Mango",\n    "Mango",\n    "Mango",\n    "Apple",\n    "Apple",\n    "Apple"\n};\n\nvar groupedStrings = listOfStrings.GroupBy(i => i)\n    .Select(i => new {i.Key, Items = i.ToList()}).ToList();\n\nvar maxGroupSize = groupedStrings.OrderByDescending(i => i.Items.Count).First()\n    .Items.Count;\n\nvar finalList = new List<string>();\n\nfor (var i = 0; i < maxGroupSize; i++)\n{\n    finalList.AddRange(from wordGroup in groupedStrings \n                        where i < wordGroup.Items.Count \n                        select wordGroup.Items[i]);\n}	0
27534160	27533917	RegEx Find Text Between Dashes	char[] delimiter = {'-'};\n   String[] arr = data.Split(delimiter,StringSplitOptions.None);\n   Console.WriteLine(arr[6]);\n   //this will return the following string\n   /*\n   N0292F060 UPTON1C UPTON/N0447F430 UL975 BARTN UP17 NOKIN UN862\n   RILES UL180 MERLY DCT GAPLI/M080F430 DCT 46N015W 45N020W/M080F470\n   37N030W 33N040W 26N050W 18N058W/N0448F470 DCT BNE DCT*/	0
12123421	12123316	How to replace / update DataRow in DataGridView	private void onUserUpdated(DataRow row)\n    {\n        int idColumn = int.Parse(row["IdColumn"].ToString());\n        foreach (DataGridViewRow DGVrow in dataGridView1.Rows)\n        {\n            if (idColumn == int.Parse(DGVrow.Cells["IdColumn"].Value.ToString()))\n            {\n                for (int i = 0; i < row.ItemArray.Length; i++)\n                {\n                    dataGridView1[i, DGVrow.Index].Value = row.ItemArray[i].ToString();\n                }\n            }\n        }\n    }	0
20969323	20969302	To retrieve image from oracle database by using imagepath in c#	byte[] file = File.ReadAllBytes(reader["imgpath"].ToString());	0
1424360	1424337	How to access the Entity Framework	using(var context = new NorthwindContext())\n{\n   var query = from p in context.ProductsSet select p;\n   // then loop through your query instance.\n}	0
5382068	5381708	ILMerge alternative, how to embed application???s dependent DLLs inside an EXE file?	using System.Runtime.CompilerServices;\n...\n    [STAThread]\n    static void Main()\n    {\n        AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>\n        {\n            // etc..\n        }\n        AvoidJitterBombing();\n    }\n\n    [MethodImpl(MethodImplOptions.NoInlining)]\n    private static void AvoidJitterBombing() {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        Application.Run(new frmrPrincipal());\n    }	0
10242041	10242010	how to select with DropDownList.text	string t = "test";\n drpFunction.Items.FindByText(t).Selected = true;	0
9271624	9271531	How to bind field to a text box	private static void CreateCommand(string queryString,\n    string connectionString)\n{\n    using (SqlConnection connection = new SqlConnection(\n               connectionString))\n    {\n        connection.Open();\n\n        SqlCommand command = new SqlCommand(queryString, connection);\n        SqlDataReader reader = command.ExecuteReader();\n        while (reader.Read())\n        {\n            Console.WriteLine(String.Format("{0}", reader[0]));\n        }\n    }\n}	0
16184175	16118894	Extracting files using SevenZip	int temp= tmp.ArchiveFileData.Count;\nif (this.progressBar1.InvokeRequired)\n        {\n            progressBar1.Invoke(new Action(delegate()\n            {\n                progressBar1.Maximum = temp;\n                progressBar1.Value = 0;\n            }));\n        }	0
16773201	16773039	How to get URL from the text	string text = "this is text with url http://test.com";\nMatch match = Regex.Match(text, @"http\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(/\S*)?$");\n\n// gets you http://test.com\nstring url = match.Value;	0
24759521	24759261	Split a string into two parts by using word	var splitOn = "App";\nvar path = "//Hello//Products//App//Images//Room//40//Tulips.jpg";\n\nvar parts = path.Split(new string[] { splitOn }, StringSplitOptions.None);\nConsole.WriteLine(parts[0] + splitOn);\nConsole.WriteLine(parts[1]);	0
16306633	16306580	unable to go into while loop in c# (with an OleDbDataReader object)	string StrCmd = "SELECT time, strike, vol FROM Table1 WHERE ((strike = @strike_value0 AND strike = @strike_value1 AND strike = @strike_value2) AND (time >= @time_value0 AND time <= @time_value1)) ";	0
32725427	32725246	How to check if a workbook is open	public static bool IsFileOpen(string path)\n    {\n        FileStream stream = null;\n        try\n        {\n            stream = File.Open(path, System.IO.FileMode.Open, System.IO.FileAccess.Read);\n        }\n        catch (IOException ex)\n        {\n            if (ex.Message.Contains("being used by another process"))\n                return true;\n        }\n        finally\n        {\n            if (stream != null)\n                stream.Close();\n        }\n\n        return false;\n    }	0
6463522	6463404	Inserting rows into DataGridView using C#	//the DataGridView\nDataGridView myDataGriView = new DataGridView();\n\n//Declare BindingSource to sync DataGridView and data table\nBindingSource myBindingSource = new BindingSource();\n\n//set the DataSource property of your BindingSource \nmyBindingSource.DataSource = myDataTable;\n\n//set the DataSource property of your DataGridView \nmyDataGridView.DataSource = myBindingSource;	0
12096643	12096559	Entity Framework DataContext Concern - Is it getting disposed properly in my controller?	protected override void Dispose(bool disposing)\n{\n   base.Dispose(disposing);\n   db.Dispose();\n}	0
2276939	2276852	In C#, convert Sql Server 2005 datetime value to another timezone	TimeZoneInfo timeZone1 = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");\nTimeZoneInfo timeZone2 = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");\nDateTime to_display= TimeZoneInfo.ConvertTime(from_db, timeZone1, timeZone2);	0
12686662	12686623	change cell background color in winform datagrid C#	private void dataGridView_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{\n    if (e.ColumnIndex == 1)\n        {\n            if ((int)e.Value == 3)\n                e.CellStyle.BackColor = Color.Blue;\n            if ((int)e.Value == 2)\n                e.CellStyle.BackColor = Color.Red;\n        }\n}	0
11150995	11150375	Check if Model is valid outside of Controller	public bool CreateCustomer(string[] data, out Customer customer)\n{\n    customer = new Customer();\n    // put the data in the customer var\n\n    var context = new ValidationContext(customer, serviceProvider: null, items: null);\n    var results = new List<ValidationResult>();\n\n    return Validator.TryValidateObject(customer, context, results, true);\n}	0
7968866	7968812	Lazy loading with the MySQL connector	var list = my_query.ToList();\nforeach (Zoo z in list)\n...	0
18996622	18996466	How to add file names on a folder to a Panel controll?	string[] filesPath = Directory.GetFiles(Server.MapPath("~/download_results/"));\n\nforeach (string fileName in filesPath)\n        {\n            string file = Path.GetFileName(fileName);\n            Panel1.Controls.Add(new LiteralControl("<div>"));\n            HyperLink hl = new HyperLink();\n            hl.Text = file;\n            hl.ID = file;\n            hl.Target = "_blank";\n            hl.NavigateUrl = "http://www.bbb.co/download_results/" + file;\n            Panel1.Controls.Add(hl);\n            Panel1.Controls.Add(new LiteralControl("</div>"));\n        }	0
767603	472389	How can I receive the "scroll box" type scroll events from a DataGridView?	using System.Reflection;\nusing System.Windows.Forms;\n\nbool addScrollListener(DataGridView dgv)\n{\n    bool ret = false;\n\n    Type t = dgv.GetType();\n    PropertyInfo pi = t.GetProperty("VerticalScrollBar", BindingFlags.Instance | BindingFlags.NonPublic);\n    ScrollBar s = null;\n\n    if (pi != null)\n        s = pi.GetValue(dgv, null) as ScrollBar;\n\n    if (s != null)\n    {\n        s.Scroll += new ScrollEventHandler(s_Scroll);\n        ret = true;\n    }\n\n    return ret;\n}\n\nvoid s_Scroll(object sender, ScrollEventArgs e)\n{\n    // Hander goes here..\n}	0
5465202	5465171	C# WPF Datagrid: Get value from SelectionChanged event	dgProperties tempItems = ((DataGrid)sender).SelectedItem as dgProperties;	0
1097167	1097129	How to get the count of enumerations?	Enum.GetNames(typeof(SomeEnum)).Length;	0
12200956	12200272	Print a ListView from my C# Web App	this.ListView1.DataBind();\n    StringWriter sw = new StringWriter();\n    HtmlTextWriter hw = new HtmlTextWriter(sw);\n    ListView1.RenderControl(hw);\n    string ListViewHTML = sw.ToString().Replace("\"", "'").Replace(System.Environment.NewLine, "");\n    StringBuilder sb = new StringBuilder();\n    sb.Append("<script type = 'text/javascript'>");\n    sb.Append("window.onload = new function(){");\n    sb.Append("var printList = window.open('', '', 'left=0");\n    sb.Append(",top=0,width=800,height=700,status=0');");\n    sb.Append("printList.document.write(\"");\n    sb.Append(ListViewHTML);\n    sb.Append("\");");\n    sb.Append("printList.document.close();");\n    sb.Append("printList.focus();");\n    sb.Append("printList.print();");\n    sb.Append("printList.close();};");\n    sb.Append("</script>");\n    ClientScript.RegisterStartupScript(this.GetType(), "ListViewPrint", sb.ToString());\n    this.ListView1.DataBind();	0
21033719	21033651	Initialize list of strings with 2 strings	public async static Task<List<String>> TagMonatJahr()\n{\n    string var1= String.Empty;\n    string var2 = String.Empty;        \n    return new List<String>{var1, var2};\n}	0
19187907	19187343	Trouble with text and linecount from textblock in wpf	public partial class MainWindow : Window\n{\n    NewWindow optionsWindow = new NewWindow();\n\n    public MainWindow()\n    {\n        InitializeComponent();\n\n        optionsWindow.button1.Click += new RoutedEventHandler(button1_Click);\n        optionsWindow.Show();\n\n    }\n\n    void button1_Click(object sender, RoutedEventArgs e)\n    {\n        double d = Convert.ToDouble(optionsWindow.textBox1.GetLineText(0));\n    }\n\n\n}	0
31656777	31656477	Search for a string in a stringbuilder and replace the whole line C#	var stringToMatch = Regex.Escape("mystring");\nvar lines = sb.ToString();\nvar regex = new Regex(string.Format(@"^.*\W{0}\W.*$", stringToMatch), RegexOptions.Multiline);\nstring result = regex.Replace(lines, "mynewstring");	0
22863494	22863244	how to use LINQ to find an object in csv file	Player selected_player = from pl in players\n                         where pl.Name == label6.Text\n                         select pl;	0
21000563	21000455	How to make an instance globally acessible in C#?	public sealed class YourSingleton\n{\n    private static readonly YourSingleton instance = new YourSingleton();\n\n    static YourSingleton() {}\n\n    private YourSingleton() { }\n\n    public static YourSingleton Instance\n    {\n        get { return instance ; }\n    }\n}	0
25979648	25979093	MailMessage is adding two dots for one dot when email is opened in Outlook or other clients	mail.BodyEncoding = System.Text.Encoding.UTF8;	0
8453834	8453697	Reading and comparing multiple XML nodes from web in c#	if ((Text1.Text == xn["Name"].InnerText) && (Text2.Text == xn["Pwd"].InnerText))\n{\n  status.Text = "Correct";\n}	0
11066791	11066727	OOP - how to call a function before the class constructor	static {\n    // code in here\n}	0
4628583	4628554	C# VS2010 Determine in application whether being debugged	Debugger.IsAttached	0
16699157	16699116	File in Use etc	File.Replace()	0
22488319	22488184	Split a string base on multiple delimiters specified by user	string data = "Car|cBlue,Mazda~Model|m3";\n            List<string> delimiters = new List<string>();\n            delimiters.Add("|c");//Change this to user input\n            delimiters.Add("|m");//change this to user input\n\n            string[] parts = data.Split(delimiters.ToArray(), StringSplitOptions.RemoveEmptyEntries);\n            foreach (string item in parts)\n            {\n                Console.WriteLine(item);   \n            }	0
4925172	4925136	Html Agility Pack + Get specific node	col.NextSibling.InnerText	0
5756288	5748361	Parse a smaller XML multiple times or a larger XML once using LINQ to XML	IEnumerable<XElement> mping = (from mpings in mpingXML.Elements("mping")\n                                           where mpings.Element("sptrn").Value.Equals(sourceURL, StringComparison.InvariantCultureIgnoreCase)\n                                           && (mpings.Attribute("lcl").Value.Equals(locale, StringComparison.InvariantCultureIgnoreCase) || mpings.Attribute("lcl").Value.Equals("ALL", StringComparison.InvariantCultureIgnoreCase))\n                                           select mpings);	0
2831116	2831082	Convert combobox string value to int	if (comboBox1.SelectedItem != null)\n    {\n        int x = int.Parse(comboBox1.SelectedItem.ToString());\n    }\n    else { //Value is null }	0
22416546	22416509	Comparing Enum Value With Integer - Assert.AreEqual	Assert.AreEqual(0, (int)Command.None);	0
4502424	4502414	Need code translation from VB to C#	[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nstatic extern bool SetForegroundWindow(IntPtr hWnd);	0
16632816	16632564	Modeless dialog box in App store	var p = new Popup();\np.Child = new MyUserControl();\np.IsOpen = true;	0
26311737	26311549	How to get a partial view Html in the controller inside a folder?	public ActionResult GetPartial()\n    {\n      var viewStr=RenderPartialToString("~/Views/Home/Partial1.cshtml",new object())\n      return content(viewStr);\n    }\n\n    // by this method you can  get string of view -- Update\n    public string RenderRazorViewToString(string viewName, object model)\n        {\n            ViewData.Model = model;\n            using (var sw = new StringWriter())\n            {\n                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,\n                                                                         viewName);\n                var viewContext = new ViewContext(ControllerContext, viewResult.View,\n                                             ViewData, TempData, sw);\n                viewResult.View.Render(viewContext, sw);\n                viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);\n                return sw.GetStringBuilder().ToString();\n            }	0
24673429	24672568	How to Implement self join to obtain complete result using Linq c#?	public Dictionary<string, string> GetEmployeesAllLevels(int managerId)\n{\n  return GetEmployeesAllLevels(managerId, null);\n}\n\nprivate Dictionary<string, string> GetEmployeesAllLevels(int managerId, Dictionary<string, string> existingList)\n{\n  if (existingList == null) existingList = new Dictionary<string, string>();\n  var lstSelectedEmployees1 = lstAllUser.Where(emp => emp.ManagerId == managerId)\n                                      .Select(emp => new { \n                                          EmployeeName = emp.UserDetail.Name, \n                                          ManagerName = emp.Manager.UserDetail.Name,\n                                          UserId = emp.UserId \n                                    }).ToList();\n  foreach(var emp in lstSelectedEmployees1)\n  {\n    existingList.Add(emp.EmployeeName, emp.ManagerName);\n    existingList = GetEmployeesAllLevels(emp.UserId, existingList);\n  }\n  return existingList;\n}	0
8898315	8898282	Regex expression for text	[a-zA-Z]{2,2}\d+	0
1737398	1737393	In C# , how can I read a connection string stored in my web.config file connection string?	string myConnectionString = ConfigurationManager\n          .ConnectionStrings["CLessConStringLocal"].ConnectionString;	0
24826107	24826021	C# Use checkBox in dataGridView and get sum rows of a column that checked is true	textBox1.Text = (dataGridView1.Rows.Cast<DataGridViewRow>()\n      .Where( r => Convert.ToBoolean(r.Cells[0].Value).Equals(true))\n      .Sum(t => Convert.ToInt32(t.Cells[1].Value))).ToString();	0
17995468	17995339	Detach event handler after attaching method with passed parameter	Action<object, MouseButtonEventArgs> myEventMethod = (sender, e) => _map_MouseLeftButtonUp2(sender, e, showResultsWindow);\n_map.MouseLeftButtonUp += myEventMethod;\n// ...\n_map.MouseLeftButtonUp -= myEventMethod;	0
6421539	6421145	Link button control using asp.net	DropDownList ddl = (DropDownList)ContentPlaceHolderID.FindControl("DropDownList1");\n        ddl.Visible = false;	0
15650484	15639568	C# code for Insert data to a table with ReferenceKey using Entity Mode	String SchooID = getNewID();\n                Schools schl = new Schools();\n                schl.school_reference = SchooID;\n                schl.school_name = "Ananda Collage";\n\n                schl.StudentReference.Value = cecbContext.Students.First(i => i.stud_name == "Josh");\n\n\n                cecbContext.AddToSchools(schl);\n                cecbContext.SaveChanges();	0
9606580	9571581	EPPlus - How to use a template	using System.IO;\nusing System.Reflection;\nusing OfficeOpenXml;\n\n//Create a stream of .xlsx file contained within my project using reflection\nStream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("EPPlusTest.templates.VendorTemplate.xlsx");            \n\n//EPPlusTest = Namespace/Project\n//templates = folder\n//VendorTemplate.xlsx = file\n\n//ExcelPackage has a constructor that only requires a stream.\nExcelPackage pck = new OfficeOpenXml.ExcelPackage(stream);	0
7173501	7173178	C# - Finding entries in database and loading user controls dynamically	MyControl control = (MyControl)Page.LoadControl("mycontrolname.ascx")	0
27901375	27901221	Reliably and definitively detect end of socket stream	00000000 00000000 00000001 11110100 and after this the 500 bytes of your actualy message comes	0
4580425	4580401	How might I define a character or string constant in C# for ASCII 127?	const char s = ((char)127);	0
25683067	25682496	format KeyEventArgs.KeyData to display in UI	string[] a = e.KeyData.ToString().Split(',');	0
28460988	28440190	Is there a way to retrieve the column names and data types a PL/SQL stored procedure returns?	var ctx = new TestContext();\nvar cmd = ctx.Database.Connection.CreateCommand() as OracleCommand;\ncmd.CommandType = CommandType.StoredProcedure;\ncmd.CommandText = "SOMESTOREDPROC";\nvar p_rc1 = new OracleParameter("p_rc1", OracleDbType.RefCursor, ParameterDirection.Output);\nvar p_rc2 = new OracleParameter("p_rc2", OracleDbType.RefCursor, ParameterDirection.Output);\ncmd.Parameters.Add(p_rc1);\ncmd.Parameters.Add(p_rc2);\n\nif (ctx.Database.Connection.State != ConnectionState.Open)\n    ctx.Database.Connection.Open();\n\nvar reader = cmd.ExecuteReader();	0
10280144	10280131	Finding faster ways to concatenate huge strings	var sb = new StringBuilder();\nsb.Append(r);\nsb.Append(g);\nsb.Append(b);\n\nstring result = sb.ToString();	0
13622409	12669667	Performance across to 2 tables, getting latest record from 2nd table	return AuditItems.OrderBy(ai => ai.DateOfAction).Last()	0
17967097	17963878	How to store a Dictionary<string,object> inside a Container in Windows 8 Metro app?	ApplicationData.Current.LocalSettings	0
19513153	19512551	MigraDoc Footer Position	AddTextFrame()	0
4865841	4864945	Wikipedia A* pathfinding algorithm takes a lot of time	var closed = new HashSet<Node>();\nvar queue = new PriorityQueue<double, Path<Node>>();\nqueue.Enqueue(0, new Path<Node>(start));\nwhile (!queue.IsEmpty)\n{\n    var path = queue.Dequeue();\n    if (closed.Contains(path.LastStep)) continue;\n    if (path.LastStep.Equals(destination)) return path;\n    closed.Add(path.LastStep);\n    foreach(Node n in path.LastStep.Neighbours)\n    {\n        double d = distance(path.LastStep, n);\n        var newPath = path.AddStep(n, d);\n        queue.Enqueue(newPath.TotalCost + estimate(n), newPath);\n    }\n}	0
33100076	33099934	Change GridView Header Text in runtime for 2 datasource in asp.net	if (e.Row.RowType == DataControlRowType.Header)\n{\n  e.Row.Cells[0].Text = "column 1";\n  e.Row.Cells[1].Text = "column 2";\n  .....\n}	0
26554900	26552629	Combine items from different rows in database and display them in one row on listview	List<ReportPermissions> finalizedItems = new List<ReportPermissions>();\n\n            foreach (ReportPermissions rp in l)\n            {\n                //Check to see if record for this user exists\n                if (!finalizedItems.Any(x => x.CwsId == rp.CwsId))\n                {\n                    // if it doesn't exist, get it\n                    ReportPermissions perm = new ReportPermissions();\n                    perm.CwsId = rp.CwsId;\n\n                    perm.Reports = string.Join(",", l.Where(x => x.CwsId == rp.CwsId).Select(x => x.Reports).Distinct());\n                    perm.Regions = string.Join(",", l.Where(x => x.CwsId == rp.CwsId).Select(x => x.Regions).Distinct());\n                    finalizedItems.Add(perm);\n                }\n            }\n\n            l= finalizedItems;	0
2552704	2552687	string splitting question	var aa = ("a" & Environment.NewLine & "b" & Environment.NewLine & "c").Split(New String[] {Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries);	0
8157339	8157279	MySQL reader usage C#	documentButtons = new RadioButton[3];\nint i = 0;\nwhile (i <= 3 && reader.Read()) { // make sure we don't get an IndexOutOfRangeException\n  documentButtons[i] = new RadioButton();\n  documentButtons[i].Text = reader["name"].ToString() + " " + (i + 1);\n\n  Console.WriteLine(reader["name"].ToString());\n\n  documentButtons[i].Location = new System.Drawing.Point(10, 10 + i * 20);\n  this.Controls.Add(documentButtons[i]);\n\n  ++i;\n}	0
22323161	22318720	I want to disable Zoom In and Out feature of web browser control in wp8	BrowserControl.LoadCompleted += Browser_LoadCompleted;\nprivate void Browser_LoadCompleted(object sender, NavigationEventArgs e)\n{\n  string myhtml = BrowserControl.SaveToString();\n  string mataTag = "<meta name=\"viewport\" content=\"width=320,user-scalable=yes\" />";\n  myhtml = html.Insert(html.IndexOf("<head>", 0) + 6, mataTag);\n  BrowserControl.NavigateToString(html);\n  BrowserControl.LoadCompleted -=  Browser_LoadCompleted;\n}	0
26039178	26037709	Serialization of Objects in ASP Web Method	[System.Xml.Serialization.XmlRoot(ElementName = "table")]        \npublic class Table\n{\n    [System.Xml.Serialization.XmlElement("row")]\n    public Row[] Rows;\n}\n\npublic class Row\n{\n    public string V;\n}	0
18755830	18750995	Connecting to SQL Server database using default connection string from C#	{\n    // connection string!\n    SqlConnection myConn = new SqlConnection("Server=localhost\\SQLEXPRESS;Integrated security=SSPI;database=Mynewdatabase;");\n\n    try\n    {\n        myConn.Open();\n        Console.WriteLine(myConn );\n    }\n    catch (System.Exception)\n    {\n       // some exception\n    }\n    finally\n    {\n        if (myConn.State == ConnectionState.Open)\n        {\n            myConn.Close();\n        }\n        myConn.Dispose();\n    }\n}	0
21915417	21914949	How to create a basic user login using asp.net-mvc?	// sign in\nFormsAuthentication.SetAuthCookie(username, false);\n// sign out\nFormsAuthentication.SignOut();	0
17484072	17483766	How to wrap text in RichTextBox	Clipboard.SetImage(Image.FromFile("full_path_of_image_here");\nrichTextBox1.Paste();	0
10795884	10795787	Importing data from XML file to SQL database	DataSet reportData = new DataSet();\nreportData.ReadXml(Server.MapPath("yourfile.xml"));\nSqlConnection connection = new SqlConnection("DB ConnectionSTring");\nSqlBulkCopy sbc = new SqlBulkCopy(connection);\nsbc.DestinationTableName = "yourXMLTable";	0
21379969	21379134	How to use RadDateInput for time in asp.net?	string _time = RadDateInput1.SelectedDate.Value.ToShortTimeString();	0
23393407	23393105	selecting a single item from grouped linq query based on a condition	DateTime dateFrom = new Date(2014,8,2);\nvar GroupedPrices = Prices\n    .Where(p => p.ArrivalDateFrom <= dateFrom && p.ArrivalDateTo > dateFrom)\n    .GroupBy(p => p.ItemID)\n    .Select(g => new{ ItemId = g.Key, NewestPrice = g.OrderByDescending(p => p.ValidFrom).First() });	0
9963888	9784575	open the new template window within c# addin in word 2007/2010	Microsoft.Office.Interop.Word.Application oWord = new Microsoft.Office.Interop.Word.Application();\nMicrosoft.Office.Interop.Word.Document oWordDoc = new Microsoft.Office.Interop.Word.Document();\nObject oMissing = System.Reflection.Missing.Value;\n\noWord.Visible = true;\n\noWord.Activate(); \n\noWord.Dialogs[WdWordDialog.wdDialogFileNew].Show(oMissing);	0
20092809	19974590	How to change WebMethod XML output for ASP.NET Webservice, specifically namespace declaration?	public LoginResult Login (\n    [XmlElement(Namespace = "")] string user,\n    [XmlElement(Namespace = "")] string password,\n    [XmlElement(Namespace = "")] string client,\n    [XmlElement(Namespace = "")] string language)\n{\n    return new LoginResult() {\n        ResultCode = 0,\n        SessionId = user + "-" + password + "-" + client + "-" + language\n    };\n}	0
15569488	15567994	Have problems with insert to TableLayoutControl	tableLayoutPanel1.SuspendLayout();\n\ntableLayoutPanel1.RowCount++;\ntableLayoutPanel1.RowStyles.Insert(tableLayoutPanel1.RowCount - 1, new RowStyle(SizeType.AutoSize));\n\ntableLayoutPanel1.SetRow(btnAdd, tableLayoutPanel1.RowCount - 1);\n\nvar control = CreateControl();\ntableLayoutPanel1.Controls.Add(control, 0, tableLayoutPanel1.RowCount - 2);\ntableLayoutPanel1.ResumeLayout();	0
1409066	1409026	how to add multiple values?	{\n   if(dg.selectedItem != null)\n   {\n      if (txt.text.length !=0)\n      {\n        txt.text = txt.text + ", ";\n      }\n      txt.text = txt.text + dg.selectedItem.text;\n   }\n}	0
10318027	10317962	Copying and pasting command prompt causes frozen console application to progress	// http://msdn.microsoft.com/en-us/library/ms686033(VS.85).aspx\n    [DllImport("kernel32.dll")]\n    public static extern bool SetConsoleMode(IntPtr hConsoleHandle, uint dwMode);\n\n    private const uint ENABLE_EXTENDED_FLAGS = 0x0080;\n\n    static void Main(string[] args)\n    {\n         IntPtr handle = Process.GetCurrentProcess().MainWindowHandle;\n         SetConsoleMode(handle, ENABLE_EXTENDED_FLAGS);	0
19956468	19956234	In C#, is there a queue which can only hold an object once in its lifetime?	class UniqueQueue<T>\n{\n    private readonly Queue<T> queue = new Queue<T>();\n    private HashSet<T> alreadyAdded = new HashSet<T>();\n\n    public virtual void Enqueue(T item)\n    {\n        if (alreadyAdded.Add(item)) { queue.Enqueue(item); }\n    }\n    public int Count { get { return queue.Count; } }\n\n    public virtual T Dequeue()\n    {\n        T item = queue.Dequeue();\n        return item;\n    }\n}	0
15264603	15264434	C# program using regex to print lines based on a value of a particular field?	appGUID:\s*(?<value>wx|null)\s	0
16850147	16849876	How to "include" a .PNG image in a binary file?	using (MemoryStream ms = new MemoryStream())\n{\n    bitmap.Save(ms);\n\n    writer.Write(ms.Length);\n    ms.Position = 0;\n    ms.CopyTo(writer.BaseStream);\n}	0
1538114	1538099	Upload file on SSL Page	If Not Request.IsSecureConnection\n    'Whatever\nEnd If	0
24599776	24533466	How to change the color scheme of Word?	const string OfficeCommonKey = @"Software\Microsoft\Office\14.0\Common";\n            const string OfficeThemeValueName = "Theme";\n            const int ThemeBlue = 1;\n            const int ThemeSilver = 2;\n            const int ThemeBlack = 3;\n\n            using (RegistryKey key = Registry.CurrentUser.OpenSubKey(OfficeCommonKey, true))\n            {\n\n                int theme = (int)key.GetValue(OfficeThemeValueName,1);\n\n                switch (theme)\n                {\n                    case ThemeBlue:\n                        //...\n\n                        break;\n                    case ThemeSilver:\n                       // ...\n\n                        break;\n                    case ThemeBlack:\n                       // ...\n\n                        break;\n                    default:\n                       // ...\n                        break;\n                }\n            }	0
18911225	18911013	Regex in C# to split string by char which can be escaped	string[] output=Regex.Split(input,@"(?<!\?)'")\n                     .Select(x=>x.Replace("?'","'"))\n                     .ToArray();	0
10006313	10006096	Initialize DataRow object with DataGridView Selected row	DataRow dr = (DataGridView1.SelectedRows[0].DataBoundItem as DataRowView).Row;	0
27438077	27438033	How to set textbox is blank for double datatypes in C#?	double? name { get; set;}	0
18651158	18588310	Retriving Last Used data in winform C#	private void Form_Load(object sender, EventArgs e)\n    {\n        if (Properties.Settings.Default.SettingName != "")\n        {\n            TextBox1.text = Properties.Settings.Default.SettingName;\n            //And so on\n        }\n    }\n\n\n\n    private void Form_FormClosing(object sender, FormClosingEventArgs e)\n    {\n        Properties.Settings.Default.SettingName = //things you want to save;\n        //Do it for the rest aswell\n    }	0
3196830	3196815	Is it possible to use C# Initialization Syntax to pass a parameter?	string[] mystrings = test.Split(new[]{ "split" }, \n    StringSplitOptions.RemoveEmptyEntries);	0
6086902	6086883	What's the best solution to implement this?	class User\n - name\n - picture\n - other properties\n\nclass Profile\n - User myAccountInfo\n - List<User> friends	0
30988745	30988496	RestSharp Serialize JSON Array to request parameter	var request = new RestSharp.RestRequest();\n\nvar locations = new Dictionary<string, object>();\nlocations.Add("A", 1);\nlocations.Add("B", 2);\nlocations.Add("C", 3);\n\nJsonObject o = new JsonObject();\n\nforeach (var kvp in locations)\n{\n    o.Add(kvp);\n}\n\nJsonArray arr = new JsonArray();\narr.Add(o);\n\nrequest.AddParameter("locations", arr.ToString());\nrequest.AddParameter("date", 1434986731000);	0
22606511	22563228	Multiple client calls after page refresh with SignalR	public UserHub()\n   {\n      Connections.Instance.OnPurge += ConnectionsUpdate\n   }	0
13395144	13395007	Using Label for logging in a WindowsForm application sometimes results in an exception - why?	delegate void myDelegate(ref Label lb, string toAdd);\nprivate void UpdateLabel(ref Label lb, string toAdd)\n{\n    if (this.InvokeRequired)\n    {\n        this.Invoke(new myDelegate(UpdateLabel), new object[] { lb, toAdd });\n    }\n    else\n    {\n        lb.Text = toAdd;\n    }\n}	0
17722563	17720220	WPF contextMenu control for bring forward and send backward	private void ContextMenuSendBackward_Click(object sender, RoutedEventArgs e)\n        {\n            Canvas parent = (Canvas)LogicalTreeHelper.GetParent(this);\n            foreach (var child in parent.Children)\n            {\n                Canvas.SetZIndex((UIElement)child, 0);\n            }\n            Canvas.SetZIndex(selected, 1);\n        }	0
23324506	23324376	How to Find strings and replace every match in File	string test = "<CrossReferenceSource Self=\"CRef\"><CrossReferenceSource Self=\"CRef\">";\n        Regex match = new Regex("CRef");\n        int count = 0;\n        string result = match.Replace(test, delegate(Match t)\n        {\n            return "CRef" + count++.ToString();\n        });	0
2584515	2584501	Finding All Characters Between Parentheses with a .NET Regex	\(([^)]+)\)	0
17481091	17481056	Convert one set of objects to another set of objects of different class in single line. C#	List<event> listOfEvents = \n    (from eachEvent in eventsFromArgus\n     select new Event(\n         ReaderName = eachEvent.DeviceName, \n         EventCode = eachEvent.EventCode, \n         EventReceivedTime = eachEvent.ReceiveTime.ToString(), \n         EventOriginTime = eachEvent.OriginTime.ToString(), \n         CardNumber = eachEvent.CredentialIdentifier)).ToList();	0
16043683	15722099	Issues Decoding Flate from PDF Embedded Font	mutool extract C:\mypdf.pdf	0
12951862	12950972	Save file in Web Application to local directory via a save dialog	try{\n            HttpContext context = HttpContext.Current;\n            context.Response.Clear();\n\n            //dts.WriteXml(Filename, System.Data.XmlWriteMode.IgnoreSchema);\n            context.Response.Write("<?xml version=\"1.0\" standalone=\"yes\"?>");\n            dts.WriteXml(context.Response.OutputStream, System.Data.XmlWriteMode.IgnoreSchema);\n            context.Response.ContentType = "text/xml";\n            context.Response.AppendHeader("Content-Disposition", "attachment; filename=" + Filename + ".xml");\n\n            context.Response.End();\n\n    }	0
26870596	26855493	DataGridView RowFilter By Date	string str = comboBox_stockDates.SelectedItem.ToString();\nDateTime date = DateTime.ParseExact(str, "dd/MM/yyyy", CultureInfo.GetCultureInfo("en-GB"));\nstring dtFilter = string.Format(\n    "[Comments_Date] >= '{0} 12:00:00 AM' AND [Comments_Date] <= '{0} 11:59:59 PM'", date.ToString("dd/MM/yyyy"));\n(dataGridView_flaggedComments.DataSource as DataTable).DefaultView.RowFilter = dtFilter;	0
19516464	19515377	Emptying a listbox programmatically	private void addImages_Click(object sender, RoutedEventArgs e)\n{ \n    ImageList.Items.Clear();\n    RefreshList();\n\n    FileInfo Images;\n    string[] filenames = null;\n    System.Windows.Forms.FolderBrowserDialog folderDlg = new System.Windows.Forms.FolderBrowserDialog();\n    folderDlg.ShowNewFolderButton = true;\n    System.Windows.Forms.DialogResult result = folderDlg.ShowDialog();\n\n    if (result == System.Windows.Forms.DialogResult.OK)\n    {\n        filenames = System.IO.Directory.GetFiles(folderDlg.SelectedPath);\n\n        foreach (string image in filenames)\n        {\n            Images = new FileInfo(image);\n\n            if(new string[]{".png", ".jpg", ".gif", ".jpeg", ".bmp", ".tif"}.Contains(Images.Extension.ToLower()))\n            {\n                ImageList.Items.Add(new LoadImages(new BitmapImage(new Uri(image))));\n            }\n        }\n    }\n\n    RefreshList();\n}\n\nprivate void RefreshList()\n{\n    // Force visual refresh of control\n    ImageList.Refresh();\n}	0
17544408	17531227	Datagridview column value displaying isssue	strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;" +\n                                        "Data Source=" + strFilePath + ";Jet OLEDB:Engine Type=5;Extended Properties='Excel 12.0;HDR=NO;IMEX=1'";	0
26268922	26268886	Create a custom string c#	int i = 111;\nstring s = "Added";\nvar s = s + i.ToString("D5");\n\n//s = "Added00111"	0
20763693	20763340	windows phone sending values with http client GET method	var response = await client.GetAsync("URL?username=user&password=password");	0
19317433	19316547	How add an item to a member of List<> array?	List<string>[] array_of_lists = new List<string>[10];\nfor (int i = 0; i < array_of_lists.Length; i++) {\n    array_of_lists[i] = new List<string>();\n    array_of_lists[i].Add("some text here");\n    array_of_lists[i].Add("some other text here");\n    array_of_lists[i].Add("and so on");\n}	0
31564593	31564366	Automapper foces subobjects to be mapped	Class A\n{\n  B b;\n}\n\nClass B\n{\n\n}	0
16132901	16132872	C# WPF Disable the exit/close button	public Window4()\n    {\n        InitializeComponent();\n        this.Closing += new System.ComponentModel.CancelEventHandler(Window4_Closing);\n    }\n\n    void Window4_Closing(object sender, System.ComponentModel.CancelEventArgs e)\n    {\n        e.Cancel = true;\n    }	0
24303985	24300055	How to get "CheckBox.Checked" item inside ListBox in Windows Phone	private void CheckBox1_Checked(object sender, RoutedEventArgs e)\n{\n    var checkBox = (CheckBox)sender;\\n    var data = (Your class)checkBox.DataContext;\n    var id = data.id;\n}	0
20615008	20614578	Fail to Keep windows service with Timer alive	static void Main(string[] args)\n    {\n        try\n        {\n            Utils.SetConfigFile();\n            ServiceBase[] ServicesToRun;\n            ServicesToRun = new ServiceBase[] \n            { \n                new TaoTimer() \n            };\n            ServiceBase.Run(ServicesToRun);\n        }\n        catch (Exception ex)\n        {\n            EventLog.WriteEntry("Application", ex.ToString(), EventLogEntryType.Error);\n        }\n     }\n\npublic partial class TaoTimer : ServiceBase\n{\n    ...\n    protected override void OnStart(string[] args)\n    {\n        SetTimerList();\n        EventLog.WriteEntry("Started");\n    }\n    ....\n}	0
3309367	3308910	How can I get StructureMap's AutoMocker to mock fake data?	[Test]\npublic void DirctoryResult_Returns_Groups()\n{\n    var service = autoMocker.Get<IGroupService>();\n    service.Expect(srv => srv.GetGroupsByQuery(Arg<string>.Is.Anything))\n        .Return(new List<CompanyGroupInfo>\n                    {\n                        new CompanyGroupInfo(),\n                        new CompanyGroupInfo(),\n                        new CompanyGroupInfo()\n                    });\n\n    service.Replay();\n\n    var directoryResult = _controller.DirectoryResult("b");\n\n    var fundDirectoryViewModel = (FundDirectoryViewModel)directoryResult.ViewData.Model;\n\n    Assert.That(fundDirectoryViewModel.Groups.Count, Is.EqualTo(3));\n\n    service.AssertWasCalled(srv => srv.GetGroupsByQuery(Arg<string>.Is.Equal("b")));\n}	0
9192717	9192534	SqlDataSource configure programmatically from code	SqlDataSource source = new SqlDataSource(connectionString:);\nsource.SelectCommand = String.Format("SELECT id, type FROM {0}" selectedTable)\nsource.DataBind();	0
2962257	2962246	Convert int string to hex string	string s = int.Parse("4322566").ToString("X");	0
6118067	6118044	How do I display user input text in a way that treats it like plain text even if it's got html tags?	lbl.Text = Server.HtmlEncode("Today is the Greatest!  <b>Hi!</b>");	0
14374898	14374797	How do I increment integers inside foreach and statement?	if(Gls.TType.Name == t.Name) \n  selectIndex++;\nelse selectIndex = 0;	0
7577141	7576805	How to detect Alt + left key in ToolStripTextBox	protected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n        if (this.ActiveControl == toolStripTextBox1.Control && keyData == (Keys.Alt | Keys.Left)) {\n            MessageBox.Show("it's special");\n            return true;\n        }\n        return base.ProcessCmdKey(ref msg, keyData);\n    }	0
748820	748239	WaitForExit for a process on a remote computer	WqlEventQuery wQuery = \n new WqlEventQuery("Select * From __InstanceDeletionEvent Within 1 Where TargetInstance ISA 'Win32_Process'");\n\nusing (ManagementEventWatcher wWatcher = new ManagementEventWatcher(scope, wQuery))\n{    \n  bool stopped = false;\n\n  while (stopped == false)\n  {\n    using (ManagementBaseObject MBOobj = wWatcher.WaitForNextEvent())\n    {\n      if (((ManagementBaseObject)MBOobj["TargetInstance"])["ProcessID"].ToString() == ProcID)\n      {\n        // the process has stopped\n        stopped = true;\n      }\n    }\n  }\n\n  wWatcher.Stop();\n}	0
3978881	3978704	Trigger before ListView change	private void ListView1_Validating(object sender, System.ComponentModel.CancelEventArgs e)\n{\n   // Show messagebox and get response\n   if(UserDoesntWantToSave)       \n   {\n      // Cancel the event\n      e.Cancel = true;\n   }\n}	0
2062621	2062540	Help with LINQ Expression	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nstatic class Program\n{\n    static void Main()\n    {\n        Func<long, long, long, IEnumerable<long>> fib = null;\n        fib = (n, m, cap) => n + m > cap ? Enumerable.Empty<long>()\n            : Enumerable.Repeat(n + m, 1).Concat(fib(m, n + m, cap));\n\n        var list = fib(0, 1, 1000).ToList();\n    }\n}	0
10769349	10769193	How do I prevent the app from terminating when I close the startup form?	[STAThread]\n    static void Main() {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n        var main = new Form1();\n        main.FormClosed += new FormClosedEventHandler(FormClosed);\n        main.Show();\n        Application.Run();\n    }\n\n    static void FormClosed(object sender, FormClosedEventArgs e) {\n        ((Form)sender).FormClosed -= FormClosed;\n        if (Application.OpenForms.Count == 0) Application.ExitThread();\n        else Application.OpenForms[0].FormClosed += FormClosed;\n    }	0
10724001	10723419	need help understanding event bubbling code in WPF	public MainWindow()\n    {\n        InitializeComponent();\n        myEllipse.AddHandler(UIElement.MouseDownEvent, new RoutedEventHandler(OnMouseDown));\n        myPanel.AddHandler(UIElement.MouseDownEvent, new RoutedEventHandler(OnMouseDown));\n        myBorder.AddHandler(UIElement.MouseDownEvent, new RoutedEventHandler(OnMouseDown));\n    }\n\n    void OnMouseDown(object sender, RoutedEventArgs e)\n    {\n        UIElement uiElement = sender as UIElement;\n        Debug.WriteLine(uiElement.GetType().ToString());\n        e.Handled = true;\n    }	0
14283724	14280180	Lotus Domino: How can I add a department's signature to an email sent through C# using Domino.dll	NotesDatabase.getProfileDocument()	0
17435591	17435470	Can I disallow other assemblies from inheriting from a class?	/// <summary>\n  /// This is a dummy constructor - it is just here to prevent classes in other assemblies\n  /// from being derived from this class. \n  /// See http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=2971840&SiteID=1\n  /// </summary>\n  internal MhlAdminLayer() { }	0
10780975	10779742	how can I get XmlNodes data with XmlDocument in similar node name?	c = Xn.ChildNodes[2].InnerText;	0
14501489	14501394	Sum LinqToSql Query Without Grouping	var query = \n    (from pd in context.Report\n     where pd.ReportDate.Month == 11\n     && pd.ReportDate.Year == 2012 \n     && pd.UserID == 11014\n     select pd).ToList() //use .ToList() to avoid doubled execution\nvar result = \n    new \n    {\n        Cost = query.Sum(pd => pd.Cost), \n        RevenueUSD = query.Sum(pd => pd.Revenue) \n    };	0
5606326	5606292	Undesired anti-aliasing when drawing bitmap on a window	pea.Graphics.InterpolationMode = InterpolationMode.NearestNeighbor;\npea.Graphics.PixelOffsetMode = PixelOffsetMode.None; // or PixelOffsetMode.Half	0
4201682	4201615	Can a type parameter of a generic class be set dynamically through a Type instance?	public IList SomeMethod(Type t)\n{ \n    Type listType = typeof(List<>);\n    listType = listType.MakeGenericType(new Type[] { t});\n    return (IList)Activator.CreateInstance(listType);\n}	0
9063890	9063836	Last Activity Date - Better Ideas for implementation	UpdateLastActivity()	0
13625204	13625143	How can I better get a collection from a collection within a collection?	private List<ListINeed> GetListINeed(Guid clientId)\n{\n    return someobject.SelectMany(p=> p.subcollection)\n                             .Select(p=>p.subObject).ToList();\n}	0
26103381	26014092	How do I prepare a list of mailaddresses to be sent to Mandrill if there are more addresses than fit in 1 request	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\npublic class Program\n{\n    public static void Main()\n    {\n        IList<int> l = new List<int>();\n        for(int i = 0; i < 5000; i++){\n            l.Add(i);   \n        }\n\n        var a = l.Take(1000); //First 1000 items\n        var b = l.Skip(1000).Take(1000); //Second 1000 items\n        var c = l.Skip(2000); //Final 3000 items\n\n        System.Console.WriteLine("a: " + a.Count());\n        System.Console.WriteLine("b: " + b.Count());\n        System.Console.WriteLine("c: " + c.Count());\n    }\n}	0
25417016	25416591	Data contract for Web API Service	public virtual AccessRequestQuestion AccessRequestQuestion {get;set;}	0
17479133	17479099	How to get the value of a combobox from its index?	DataRowView itemAtFourthIndex = combobox.Items[4] as DataRowView;\n\nint id = -1;\nif(itemAtFourthIndex != null)\n   id = Convert.ToInt32(itemAtFourthIndex.Row["ID"]);	0
12013919	12013792	how to get number of items in listbox	TextBox1.Text = ListBox1.Items.Count.ToString();	0
22939980	22939917	delete item from observablecollection make the XML serialize update fail	using (IsolatedStorageFileStream fsIdea = new IsolatedStorageFileStream("Idea.xml", FileMode.Create, storage))	0
2252023	2251974	NULL values in object properties in Entity Framework	var comm = from u in my_bd.Comment.Include("Article").Include("Author")\n           where ......\n           select u;	0
27308417	27308391	How to call constructor with 2 arguments from a no argument constructor?	public Instrument() : this(DefaultName, DefaultCategory)\n{\n\n}	0
5913558	5907502	Image's menu doesnt open on left click in XP	buttonHelp.ContextMenu.Placement = System.Windows.Controls.Primitives.PlacementMode.Bottom;\nContextMenuService.SetPlacement(buttonHelp, System.Windows.Controls.Primitives.PlacementMode.Bottom);	0
34500722	34500474	C# / .NET: Get all windows with a stay on top flag	public static bool IsWindowTopMost(IntPtr Handle)\n{\n  return (GetWindowLong(Handle, GWL_EXSTYLE) & WS_EX_TOPMOST) != 0;\n}	0
10225787	10082320	How to see whether "include inheritable permissions" is unchecked for a file or folder?	DirectoryInfo d = new DirectoryInfo(@"e:\test1");\nDirectorySecurity acl = d.GetAccessControl();\nif (acl.GetAccessRules(false, true, typeof(System.Security.Principal.SecurityIdentifier)).Count >0)\n    // -- has inherited permissions\nelse\n    // -- has no inherited permissions	0
11442951	11404739	STE Update & Delete struggle in an N-TIER application	public bool UpdateUser(User userToUpdate)\n{\n    using (DBContext _context = new DBContext())\n    {\n        try\n        {\n            User outUser = usersModel.Users.Single(x => x.UserId == userToUpdate.UserId);\n            outUser = userToUpdate;\n            _context.ApplyCurrentValues("Users", outUser);\n            _context.SaveChanges();\n            return true;\n        }\n        catch (Exception ex)\n        {\n            // LOGS etc.\n            return false;\n        }\n    }\n}	0
6457528	6457474	EventHandler with custom arguments	menuItemFolder.Click += (sender, e) => YourMethod(owner, dataType);	0
12387327	11862069	ASP.NET MVC4 WebAPI: optional parameters	public string GetFindBooks(string author="", string title="", string isbn="", string  somethingelse="", DateTime? date= null) \n{\n    // ...\n}	0
11003670	11003566	MySQL online database	public class RecordsController : ApiController\n{\n    public HttpResponseMessage Post(Record record)\n    {\n        var newId = _Records.Count + 1;\n        record.ID = newId;\n        _Records.Add(record);\n        var newMessage = new HttpResponseMessage<Record>(record);\n        return newMessage;\n    }\n }	0
1434371	1288946	WMD Markdown showing in preview div	output:"HTML"	0
30706943	30706630	How to Pass Dynamic Values in Xpath	//webDriver.FindElement(By.XPath("//*[contains(@id,"ChassisId')]/a/ins[contains(text(),'POWER CONNECT')]")	0
4621712	4589021	Get other ldap query strings associated with a domain	IEnumerable<SearchResult> Search(string domain, string filter)\n{\n    DirectoryContext context = new DirectoryContext(DirectoryContextType.Forest, domain);\n    Forest forest = Forest.GetForest(context);\n    GlobalCatalog gc = null;\n    try\n    {\n        gc = forest.FindGlobalCatalog();\n    }\n    catch (ActiveDirectoryObjectNotFoundException)\n    {\n        // No GC found in this forest\n    }\n\n    if (gc != null)\n    {\n        DirectorySearcher searcher = gc.GetDirectorySearcher();\n        searcher.Filter = filter;\n        foreach (SearchResult result in searcher.FindAll())\n        {\n            yield return result;\n        }\n    }\n    else\n    {\n        foreach (Domain d in forest.Domains)\n        {\n            DirectorySearcher searcher = new DirectorySearcher(d.GetDirectoryEntry(), filter);\n            foreach (SearchResult result in searcher.FindAll())\n                yield return result;\n        }\n    }\n}	0
8152495	8152415	a list of dynamic functions and dynamically calling them	var list = new List<dynamic>\n          {\n               new Func<int, int, int> (X),\n               new Func<int, int, string, string> (Y)\n          };\n\ndynamic result = list[0](1, 2); // like X(1, 2)\ndynamic result2 = list[1](5, 10, "hello") // like Y(5, 10, "hello")	0
17597231	17597066	Compare a list of objects to an object	...\nbool candidatExists = false;\nint idCandidat = int.Parse(Session["Id_candidat"].ToString());\nwhile (dr.Read())\n    {\n        cv p3 = new cv();\n        p3.Id_candidat = int.Parse(dr[0].ToString());\n        c.Add(p3);\n        if(p3.Id_candidat == idCandidat)\n        {\n             candidatExists = true;\n        }\n    }\n    dr.Close();\n    con.Close();\n\n    Button1.Enabled = !candidatExists;	0
31199907	31199668	How do I parse this JSON Result as an object?	using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing Newtonsoft.Json;\n\nclass Test\n{ \n    static void Main(string[] args) \n    {\n        var json = File.ReadAllText("weather.json");\n        var root = JsonConvert.DeserializeObject<Root>(json);\n        Console.WriteLine(root.Weather[0].Description);\n    }\n}\n\npublic class Root\n{\n    // Just a few of the properties\n    public Coord Coord { get; set; }\n    public List<Weather> Weather { get; set; }\n    public int Visibility { get; set; }\n    public string Name { get; set; }\n}\n\npublic class Weather\n{\n    public int Id { get; set; }\n    public string Description { get; set; }\n}\n\npublic class Coord\n{\n    public double Lon { get; set; }\n    public double Lat { get; set; }\n}	0
11123741	11123639	How to resolve hostname from local IP in C#.NET?	using System.Net;\n...\n\npublic string GetHostName(string ipAddress)\n{\n    try\n    {\n        IPHostEntry entry = Dns.GetHostEntry(ipAddress);\n        if (entry != null)\n        {\n           return entry.HostName;\n        }\n    }\n    catch (SocketException ex)\n    {\n       //unknown host or\n       //not every IP has a name\n       //log exception (manage it)\n    }\n\n    return null;\n}	0
8948497	8948417	How to delete a folder asynchronously	Task.Factory.StartNew(path => Directory.Delete((string)path, true), fullPath);	0
26200432	26200351	autoincrement value on click asp.net C#	protected void Page_Load(object sender, EventArgs e)\n{\n    ViewState["autogen"] = 0;\n}\n\nprotected void Button1_Click(object sender, EventArgs e)\n{\n    var autogen = Convert.ToInt32(ViewState["autogen"]);\n    Label1.Text = autogen.ToString();\n    ViewState["autogen"] = autogen + 1;\n}	0
12138968	12138808	c# object to xml	System.Web.HttpUtility.HtmlEncode("&")	0
4777962	4777855	Silverlight 4 C# - How to get value of SelectedItem from a listbox?	ListBoxItem selected = listBox1.SelectedItem as ListBoxItem;\n\nMessageBox.Show(selected.Content.ToString());	0
8315364	8260044	Sync Framework Client must win scenario	destinationProvider.Configuration.ConflictResolutionPolicy =   ConflictResolutionPolicy.DestinationWins;	0
1773879	1773825	How do you return something in a ActionFilterAttribute?	public override void OnAuthorization(AuthorizationContext filterContext)\n{\n    if (...subscriptionExpired...)\n    {\n        filterContext.Cancel = true;\n        filterContext.Result = new RedirectResult("/user/login");\n    }\n}	0
1129947	1129918	Event handling in class file in C# windows application	Application.Idle += Initialize;\nApplication.Run();\n...\n\nprivate void Initialize (object sender, EventArgs e) \n{ \n  Application.Idle -= Initialize; \n  _hook = new KeyboardHook();\n\n  // this must be performed from the thread running Application.Run!\n  // do not move it out of this event handler\n  _hook.RegisterHotKey (...);      \n}	0
7031892	7000424	Looking up a value in another datatable when creating a report viewer report	TestDataSetTableAdapters.CategoryTableAdapter ca = new TestDataSetTableAdapters.CategoryTableAdapter();\n        this.ds1 = new TestDataSet();\n        ca.Fill(this.ds1.Category);	0
29312817	29312742	Convert list to array in c#	[WebMethod]\npublic static Student[] GetStudents()\n{        \n    String connectionString = ConfigurationManager.ConnectionStrings["str"].ConnectionString;\n    using(SqlConnection con = new SqlConnection(connectionString))\n    using(SqlCommand cmd = con.CreateCommand())\n    {\n        cmd.CommandText = "SELECT * FROM [student]";\n        con.Open();\n\n        List<Student> ret = new List<Student>();\n\n        using(SqlDataReader rdr = cmd.ExecuteReader())\n        {\n            while(rdr.Read())\n            {\n                ret.Add( new Student() {\n                    Name = rdr.GetString("Name"),\n                    Address = rdr.GetString("Address"),\n                    Sex = rdr.GetString("Sex"),\n                    Email = rdr.GetString("Email")\n                } );\n            }//while\n        }//using\n\n        return ret.ToArray();\n    }//using \n}//GetStudents	0
16794765	16793756	How to count and rename duplicate rows in a DataTable	foreach(DataRow row in thisTable.Rows)\n    {\n        string name = row.Item[0].ToString();\n\n        if(name[name.Length - 3] == '(' && name[name.Length - 1] == ')')\n            continue;\n\n        string item = row.Item[1].ToString();\n        int quantity = Convert.ToInt32(row.Item[2]);\n        string expression = "Name = " + name + " and Item = " + item + " and Quantity = " + quantity;\n\n        DataRow[] matchingRows = table.Select(expression);\n        for(int i = 1; i < matchingRows.Length; i++)\n            matchingRows[i]["Name"] += " (" + i + ")";  \n    }	0
11657145	11642852	Add an existing PDF from file to an unwritten document using iTextSharp	public MemoryStream MergePdfForms(List<byte[]> files)\n{\n    if (files.Count > 1)\n    {\n        PdfReader pdfFile;\n        Document doc;\n        PdfWriter pCopy;\n        MemoryStream msOutput = new MemoryStream();\n\n        pdfFile = new PdfReader(files[0]);\n\n        doc = new Document();\n        pCopy = new PdfSmartCopy(doc, msOutput);\n\n        doc.Open();\n\n        for (int k = 0; k < files.Count; k++)\n        {\n            pdfFile = new PdfReader(files[k]);\n            for (int i = 1; i < pdfFile.NumberOfPages + 1; i++)\n            {\n                ((PdfSmartCopy)pCopy).AddPage(pCopy.GetImportedPage(pdfFile, i));\n            }\n            pCopy.FreeReader(pdfFile);\n        }\n\n        pdfFile.Close();\n        pCopy.Close();\n        doc.Close();\n\n        return msOutput;\n    }\n    else if (files.Count == 1)\n    {\n        return new MemoryStream(files[0]);\n    }\n\n    return null;\n}	0
25727894	25727567	how to connect two connection strings and insert data from one database into another MySQL database	string sql="";\nforeach(DataRow dr in yourdatatable.Rows){\n   sql += "INSERT INTO table2 (column1) VALUES ('"+dr["something"]+"'); ";\n}\n//and here execute this sql	0
28905722	28905187	How to introduce a delay in actions for my Windows 8 app	DispatcherTimer timer = new DispatcherTimer();\n\n// Call this method after the 60 seconds countdown.\npublic void Start_timer()\n{        \n    timer.Tick += timer_Tick;\n    timer.Interval = new TimeSpan(0, 0, 5);\n    bool enabled = timer.IsEnabled;\n\n    // Check and show answer is correct or wrong\n\n    timer.Start();       \n}\n\nvoid timer_Tick(object sender, object e)\n{\n    this.Visibility = System.Windows.Visibility.Visible;\n    (sender as DispatcherTimer).Stop(); // Or you can just call timer.Stop() if the timer is a global variable.\n\n    // Clear screen, go to the next question\n}	0
26666820	26666661	Unity3D's Vector3 Declaration in C#	Vector3 vectorB;\nvectorB.x = 1;\nDebug.Log("vectorB: " + vectorB);  // <--CS0165: Use of unassigned local variable	0
31315197	31293979	Visual Studio Regex matching repeated string	var methods = Assembly.GetExecutingAssembly()\n        .GetTypes()\n        .SelectMany( t => t.GetMethods() )\n        .Where( m => m.GetCustomAttributes( typeof ( MyAttribute ), true ).Any() && m.IsPublic && m.GetParameters().Length == 0 )\n        .ToList();\n\n     methods.ForEach( m => Debug.WriteLine( m.Name ) );	0
3727361	3727261	Is it possible to convert an array of strings into one string?	Regex r = new Regex(@"CREATE TABLE [^(]+((.*)) ON", RegexOptions.SingleLine);	0
24060052	24059494	Date format automatically changing when using JSON.net	JsonReader jsonReader = new JsonTextReader(new StringReader(json)) { DateParseHandling = DateParseHandling.None };\ndynamic jsonObj = JObject.Load(jsonReader);	0
9002618	9002546	Inserting an item with a specific color in a listbox	private void listBox_DrawItem(object sender, DrawItemEventArgs e)\n{\n    e.DrawBackground();\n    Graphics yourObj = e.Graphics;\n\n    yourObj .FillRectangle(new SolidBrush(Color.Red), e.Bounds);\n\n    e.DrawFocusRectangle();\n}	0
4951749	4951638	C# how to lock the file	s = filePath + "s";\nnewS = targetFullPath2 + "s";\nFile.Copy(s, newS + "_", true);    // add the _ so the other process\n                                   // doesn?t ?see? the file yet\n\ndtFileCreation = File.GetCreationTime(s);\nFile.SetCreationTime(newS + "_", dtFileCreation);\n\n// We?re done with the file, now rename it to its intended final name\nFile.Move(newS + "_", newS);	0
29689727	29689686	C# List of List of Lines Index was out of range	contiguousLines.Add(new List<line>());\ncontiguousLines[columnNum].Add(freeLines[0]);	0
27512280	27512173	How to force method to use a mock?	public interface IWpManagerFactory\n{\n    WpManager BuildWpManager();\n}\n\npublic sealed class Tests\n{\n    public void Test()\n    {\n        var manager = new Mock<WpManager>();\n        //Set up mock manager here...\n\n        var factory = new Mock<IWpManagerFactory>();\n        factory.Setup(f => f.BuildWpManager()).Returns(manager.Object);\n\n        //Inject factory to class under test and execute the method under test...\n    }\n}	0
19544866	19544533	Add TransformGroup to a TransformGroup in wp7	var textBox = new TextBox();\n      var transformGroup = new TransformGroup()\n          {\n              Children = new TransformCollection()\n                  {\n                      new MatrixTransform(), \n                      new TransformGroup\n                      { \n                          Children = new TransformCollection()\n                          {\n                              new ScaleTransform(), \n                              new RotateTransform(), \n                              new TranslateTransform()\n                          }\n                      }\n                  }\n          };\n\n      textBox.RenderTransform = transformGroup;	0
10909507	10909078	How can i add vb.net dll into c# application	ilmerge /target:library /out:YourLib.dll ClassLibrary1.dll ClassLibrary2.dll	0
32402235	32402096	Counting a character and display in toolStripStatusLabel	var vowels = new char[]{ 'a', 'e', 'i', 'o', 'u' };\nvar vowelCount = rtbText.Text.Count(c => vowels.Contains(c));\nvar characterCount = rtbText.Text.Length;\ntoolStripStatusLabel1.Text = characterCount + " characters, of which " \n    + vowelCount + " are vowels.";	0
19539070	19535587	OnClick event not working for linkbutton in a master page	if (!Page.IsPostBack)\n{\n      // Your code here\n}	0
1913215	1913200	how to split a string into an array but only split on the first instance of a character (space in this case)	"ABC DEF EFG".Split(new char[] { ' ' }, 2)	0
18851136	18850933	How to use an HTML file in WPF	Uri uri = new Uri(AppDomain.CurrentDomain.BaseDirectory + @"\Rule1.html");	0
2458124	2458103	View Lambdas in Visual Studio Debugger	var q = _ctx.DBList \n     .Where(x => x.AGuidID == paramID)  \n     .Where(x => x.BBoolVal == false) \n// view q in the debugger to see the SQL it will generate\nvar myList = q.ToList();	0
6754323	6754244	indexof a string from a list in another list	foreach (var str in usedCSS)\n{\n    if (CSS.Any( x=> x.StartsWith(str))\n        Response.Write(str);\n    else\n        Response.Write("Could not find: " + x + "<br />");\n}	0
7271879	7270260	Understanding Icon Indicies in a C# Application	int main(void) { return 0; }	0
5021884	5018352	LINQ to Entities - assigning many to many relations	internal void UpdateMedia(int mediaID, int[] catagoryIDs)\n{\n    using (Data.EFEntities context = new Data.EFEntities())\n    {\n        Data.Media media = context.Media.Single(m => m.MediaID == mediaID);\n\n        foreach(var category in context.Category.Where(cat => catagoryIDs.Contains(cat.CategoryID))\n        {\n            media.Categories.Add(category);                \n        }\n\n        context.SaveChanges();\n    }\n}	0
6329802	6329423	Passing arguments to a shell script from C# process	ProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.CreateNoWindow = false;\nstartInfo.UseShellExecute = false;\nstartInfo.FileName = "YourFile.exe";\nstartInfo.WindowStyle = ProcessWindowStyle.Hidden;\nstartInfo.Arguments = "";//Arguments should be here\nusing (Process exeProcess = Process.Start(startInfo))\n{\n    exeProcess.WaitForExit();\n}	0
6586847	6586714	How to Install a service as the current account in c#	processInstaller.Account = ServiceAccount.User;\nprocessInstaller.User = "domain\username";\nprocessInstaller.Password = "Password";	0
25754723	25754469	Receiving a Base64 encoded string from Android into C# application	encodedIcon = encodedIcon.Replace(@"\n", "");\nif(encodedIcon.Length % 4 != 0)\n    // we may have 0, 1 or 2 padding '='\n    encodedIcon += new string('=', 4 - encodedIcon.Length % 4);\nbyte[] arr = System.Convert.FromBase64String(encodedIcon);	0
1237488	1237425	Insert whitespace between characters in listbox	string spaces = "& nbsp;& nbsp;& nbsp;& nbsp;"; // without spaces after &\n        spaces = Server.HtmlDecode(spaces);\n\n        lt.Text = ItemName + "spaces" + barcode + "spaces" + price; // works	0
16746356	16684956	add custom where condition with user in easyquery	SqlQueryBuilder builder = new SqlQueryBuilder((DbQuery)query);\n  builder.BuildSQLEx("", "users.user_id=" + loggedUser.id);\n  string sql = builder.Result.SQL;	0
25429863	25429823	Remove all but the highest value from a List grouped by another property using LINQ	var endResult = reviewList.OrderByDescending(e => e.Amount)\n             .GroupBy(e => e.Name)\n             .Select(g => g.First());	0
14499624	14499268	How to return a view from parent controller in MVC	filterContext.Result = View(someParameter);	0
21748992	21748824	How can I keep catching exceptions, in a way that would allow me to resume whatever I'm doing?	if (pinfo.CanWrite) {\n        try {\n            pinfo.SetValue(comp, pinfo.GetValue(other, null), null);\n        }\n        catch { }\n    }	0
16438247	16438181	Print First Letter of Each Word in a Sentence	string inputString = "Another One Bites The Dust And Another One Down";\nstring[] split = inputString.Split();\nforeach (string s in split)\n{\n    Console.Write(s.Substring(0,1));\n}	0
1139152	1139133	Whats the best way to store a version number in a Visual Studio 2008 project?	Assembly.GetExecutingAssembly().GetName().Version	0
1962817	1962810	Convert date into the format dd-mm-yyyy	DateTime.TryParse(12/24/2009 12:48:00 PM,out registereddate);\n  strregdate = registereddate.ToString("dd-MM-yy");	0
25523254	25522972	Sorting a BsonArray of string	var array = new BsonArray(new []\n                {\n                    "BO0001",\n                    "CO0001",\n                    "BD0002",\n                    "BD0001"\n                });\n\nvar sortedArray = new BsonArray(array.OrderBy(v => v.AsString));\n\nforeach (var v in sortedArray)\n    Console.WriteLine(v);	0
23828141	23828042	Assign values to members of a list	for(int i = 0; i < studentsWithNoGroupId.Count; i++)\n{\n  if((i % 3) == 0)\n   groupid += 1;\n  studentsWithNoGroupId.ElementAt(i).groupId = groupid;\n}	0
20396992	20396945	Convert SQL Datetime to C# Date	if(dt.HasValue)\n{\n    newDt = dt.Value.ToString("yyyy-MM-dd");\n}	0
6829522	6829463	How to perform automatic button click on Windows Form based on a Parameter? C#	private void Button1_Click(object sender, EventArgs e)\n{\n    DoSomething();\n}\n\nprivate void Sensex_Prediction_Form_Load(object sender, EventArgs e)\n{\n    if(Inovker == "X")\n    {\n        DoSomething();\n    }\n}\n\nprivate void DoSomething()\n{\n    ...\n}	0
198446	190476	Is there a way to write a group by query in LinqToSql grouping not on a scalar value?	var awGroups = from aw in _repository.GetAws()\ngroup aw by aw.AwType.ID into newGroup  //changed to group on ID\nselect newGroup;\n\nList<KeyValuePair<AwType, int>> RetGroups = new List<KeyValuePair<AwType, int>>();\nforeach (var group in awGroups)\n{\n    //changed to get the first element of the group and examine its AwType\n    RetGroups.Add(new KeyValuePair<AwType, int>(group.First().AwType, group.Count()));\n}\nreturn RetGroups;	0
8130669	8117144	combined primary key search in DataTable	int rowIndex = dt.Rows.IndexOf(dt.Select("ITEM_CODE = 'i001' AND WAREHOUSE_CODE='001' AND LOTNO='111'")[0]);	0
1686765	1685974	How to capture blocks of repetating text using regular expression?	(\n|\r|\a|\f)(\s|\d|\.|\))*?(?<id>(Client|Customer|Role|Organi(s|z)ation|Vendor|Company|Employer))(\s|\S)*?(?=(\n|\r|\a|\f)(\s|\d|\.)*?(\k'id'))*?	0
12664642	12662785	Notify source of target changes in TwoWay Binding	class TaskItem, INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n    internal void NotifyPropertyChanged(String info)\n    {\n        if (PropertyChanged != null)\n        {\n            PropertyChanged(this, new PropertyChangedEventArgs(info));\n        }\n    }\n\n    private string title;\n    public string Title \n    { \n       get { return title; } \n       set \n       { \n           if (title == value) return;\n           title = value;\n           NotifyPropertyChanged("Title");\n       }\n    }\n    public TaskItem (string -title) \n    { title = _title; }  \n    // does not fire setter title lower case \n    // but the UI will have this value as ctor fires before render \n    // so get will reference the assigned value of title \n}	0
4982845	4982823	SQL Update multiple rows in a single query	"UPDATE PricePlan \n       SET price =\n                 IIf(PricePlanName = 'Guest',"+ GuestInput.Text + ",\n                   IIf(PricePlanName = 'Member',"+ MemberInput +"))"	0
30976073	30916925	Treeviewitem focus prevents contextmenu from showing	e.Handled = true;	0
8200393	8200383	How to get DateTime month in  upper case?	DateTime CusDate = dateTimePicker1.Value;\n    string Date = CusDate.ToString("ddMMMyyyy").ToUpper();	0
15666442	15666200	Using the value present in String type variable as tablename	public void addCurriculumData(String StoredProcName,Table table)	0
9949219	9948801	Parsing XML using LINQ	var doc = XDocument.Parse(@"Your giant xml string here");\nvar books =\n    doc\n        .Descendants("book")\n        .Select(bookElement => \n        new\n        {\n            Title = bookElement.Descendants("title").Single().Value, \n            Authors = bookElement.Descendants("author")\n                .Where(authorElement => authorElement.Descendants("country").Single().Value == "USA")\n                .Select(authorElement => authorElement.Descendants("name").Single().Value)\n        });\n\nforeach(var book in books)\n{\n    Console.WriteLine("Book: " + book.Title);\n    Console.WriteLine("Authors: " + string.Join(",", book.Authors));\n}	0
13000845	12955673	How to change the height of Kendo ui Grid	.Scrollable(scr=>scr.Height(230))	0
5997610	5997549	How do I invoke a method in another thread?	public void ConnectButtonPressed()\n            {\n                var threadedTask = () => m_Model.Connect(m_View.Hostname, m_View.Port);\n                threadedTask.BeginInvoke(null,null);\n            }	0
6001539	6001306	How to solve stringBuilder fragmentation? 	sb1 = new StringBuilder(4200000);	0
1553534	1544351	Handling a SAFEARRAY returned from C# server	IMyRecords** pIMyRecords; \nHRESULT hr = SafeArrayAccessData(pMyRecordsSA, (void**)&pIMyRecords);	0
30476163	30434876	How to get the status of apps in Win8.1 task manager?	tasklist /apps /fi "STATUS eq SUSPENDED"	0
20462094	19356208	javascript username password https login issue for windows phone 8	browser.InvokeScript("eval", "document.getElementById('Login1_UserName').value = '" + username + "';");\n browser.InvokeScript("eval", ("document.getElementById('Login1_Password').value = '" + password + "';"));\n browser.InvokeScript("eval", string.Format("document.getElementById('Login1_LoginButton').click();"));	0
18062005	18061240	Keeping CPU Usage Low for a certain amount of time. c#	int secondsWhileLowUsage = 0;     \ndo {\n    cpuUsage = new PerformanceCounter("Processor", "% Processor Time", "_Total");\n    var usage = cpuUsage.NextValue();\n    do\n    {\n        Thread.Sleep(TimeSpan.FromSeconds(1));\n        usage = cpuUsage.NextValue();\n        if (usage > 10.00)\n            secondsWhileLowUsage = 0;\n\n        Console.WriteLine(usage + "%");\n    } while (usage > 10.00);\n    secondsWhileLowUsage ++; \n} while (secondsWhileLowUsage < 5)\n\nProcess proc = new Process();\nproc.StartInfo = new ProcessStartInfo(@"C:\Documents and Settings\rcgames\Desktop\Game1.exe");\nproc.Start();	0
21965283	21965198	List element splitting	using System.IO;\nusing System;\nusing System.Collections.Generic;\n\nclass Program\n{\n    static void Main()\n    {\n\n        List<string> lstrSample = new List<string>();\n        lstrSample.Add("1 - 12/2015 - 12/2016");\n        lstrSample.Add("2 - 12/2015 - 12/2016");\n        List<string> lstrResult = new List<string>();\n        foreach(string curStr in lstrSample)\n        {\n            lstrResult.Add(curStr.Replace(" ","").Split('-')[0]);\n        }\n        foreach(string s in lstrResult)\n        {\n            Console.WriteLine(s);\n        }\n    }\n}	0
6408996	6408954	How to display correctly this string on an alert javascript	alert('Citt??')	0
23651428	23584510	EventFiringWebDriver finds a IWebElement that does NOT implement IWrapsDriver	public static IWebDriver GetDriver(this IWebElement element)\n    {\n        IWrapsDriver wrappedElement = element as IWrapsDriver;\n        if (wrappedElement == null)\n        {\n            FieldInfo fieldInfo = element.GetType().GetField("underlyingElement", BindingFlags.NonPublic | BindingFlags.Instance);\n            if (fieldInfo != null)\n            {\n                wrappedElement = fieldInfo.GetValue(element) as IWrapsDriver;\n                if (wrappedElement == null)\n                    throw new ArgumentException("Element must wrap a web driver", "element");\n            }\n        }\n\n        return wrappedElement.WrappedDriver;\n    }	0
25730448	25730156	Sort by alphabetically and quantity in same list	var query = items.GroupBy(item => item.Name)\n    .OrderByDescending(group => group.Count())\n    .SelectMany(group => group);	0
34526562	34462431	How I can convert void pointer to struct in C#	[StructLayout(LayoutKind.Sequential, Pack = 1, Size=255, CharSet = CharSet.Ansi)]\npublic struct Menu\n{\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]\n    public string str1;\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 255)]\n    public string str2;\n}\n\npublic static unsafe int fnSys(Menu value)\n{\n    if (value!=null)\n    {\n        System.Windows.Forms.MessageBox.Show("msg");\n    }\n\n    return 1;\n}	0
4314651	4314567	.Net Multiline Regex expression to restrict to integers	(\d?\\n*)?	0
11015599	11015527	Extract the contents of a string between two string delimiters using match in C#	var doc = new HtmlDocument();\n\nusing (var wc = new WebClient())\nusing (var stream = wc.OpenRead(url))\n{\n    doc.Load(stream);\n}\n\nvar table = doc.DocumentElement.Element("html").Element("body").Element("table");\nstring tableHtml = table.OuterHtml;	0
4695419	4695368	Unhandeled exception in application	\\tkahd-nti-1\TrackIt\Audit32.exe	0
17797572	17797470	add a ListViewItem to two or more ListView Items Collection?	foreach(var p in listProf)\n{\n    var item = new ListViewItem{Text = p.Name, Tag = p};\n    ListView1.Items.Add(item);\n    ListView2.Items.Add((ListViewItem)item.Clone());\n}	0
26144792	26143269	Use a value from reflection in a LINQ query	var entity1 = Expression.Parameter(typeof(Entity));\nvar nameFilterExp = Expression.Call(\n    Expression.Property(entity1, firstOrDefault.PropertyInfo.Name),\n    typeof(string).GetMethod("Contains", new[] { typeof(string) }),\n    Expression.Constant(nameFilter)\n);\nvar predicate = Expression.Lambda<Func<Entity, bool>>(\n    type == HandledType.Doubtful\n        ? (Expression)Expression.AndAlso(Expression.Equal(Expression.Property(entity1, "IsDoubtful"), Expression.Constant(true)), nameFilterExp)\n        : (Expression)nameFilterExp,\n    entity1);\nentities = entities.Where(predicate);	0
11439215	11439169	Option in rewriting some nested if statements	if (typology.Name == nameOriginalValue || IsUniqueName(typology.Name))\n{\n    _typologyRepository.Update(typology);\n    _typologyRepository.Save();\n}\nelse\n{\n    _validatonDictionary.AddError("Name", errorMessageNameUnique);\n}	0
10255731	10255718	Advantages of declaring Reference Libraries in C#?	using Num = System.Numerics.BigInteger;	0
23813893	23813799	How to remove less than hundred fraction of a decimal	decimal d =7526.50m;\ndecimal truncated = d - (d % 100);	0
25668857	25657106	Creating a document in BaasBox using HttpClient?	//Step 3: Create the content body to send\nstring sContent = string.Format("{\"fname\":\"{0}\",\"lname\":\"{1}\",\"age\":\"{2}\",\"gender\":\"{3}\"}", sFirstName, sLastName, sAge, sGender);	0
16674834	16658495	How to convert EmailMessage alternate views into SendGrid Html and Text	mail.AlternateViews[0]	0
3654408	3632928	WPF: Data binding & Display member path	public override string ToString()\n   {\n      return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}]", new object[] {  base.GetType().Name, this.Name });\n    }	0
14573668	14573650	String.Format: Input string was not in a correct format	"{{ cmd: \"save magellan deal\", data: {{ id: {0} , AId: {1}, " +\n"CId: {2}, CCId:{3}, LA: \"{4}\", BA: \"{5}\" , " +\n"LSA: \"{6}\" , BSA: \"{7}\" , \"path: \"{8}\"," +\n"dscp: \"{9}\", SI: \"{10}\", CD: \"{11}\", " +\n"period: \"{12}\", IsStatic: {13}, LSD: {14}, LC: {15}, RB: {16},}} " +\n"Notes: \"{17}\", IsEE: {18}, RBy: {19}, DPDD: \"{20}\", LId: {21} }} }}"	0
20807156	20806773	including Closure Compiler into an asp.net app	java -jar compiler.jar --js hello.js --js_output_file hello-compiled.js	0
13072483	13070206	Represent a self reference table in a text tree	static void Main(string[] args)\n    {     \n        List<Group> groups = new List<Group>();               \n        ...\n        PrintTree(groups, "", null);\n    }\n\n    static void PrintTree(List<Group> allGroups, string lead, int? id)\n    {\n        var children = allGroups.Where(g => g.ParentID == id).ToList();\n\n        if (children.Count > 0)\n        {\n            int n = children.Count-1;\n\n            for (int i = 0; i < n; i++)\n            {\n                Console.WriteLine(lead + "???" + children[i].Name);\n                PrintTree(allGroups, lead + "?  ", children[i].ID);                    \n            }\n\n            Console.WriteLine(lead + "???" + children[n].Name);\n            PrintTree(allGroups, lead + "   ", children[n].ID);                    \n        }\n    }	0
12263463	12263433	Some trouble with subclass constructor	class B : A\n{\n  public class B(string id, int size) : base(id, size) \n  { \n     this.Name = "Name2";\n  }\n}	0
30670254	30670145	C# adding/subtracting/multiplying/dividing different items in listbox based on first character of item	switch (line[0])\n{\n    case '+':\n        num += Convert.ToInt32(line.Substring(1));\n        break;\n    case '-':\n        num -= Convert.ToInt32(line.Substring(1));\n        break;\n}	0
7451526	7450958	Generic type from string value	typeHandler.InvokeMember("Handle", BindingFlags.InvokeMethod, null, handler, new[] { requestItem });	0
581574	581570	How can I create a temp file with a specific extension with .net?	string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";	0
15401793	15401735	Programmatically creating a Wireless Access Point in C#	netsh wlan set hostednetwork mode=allow ssid=<NetworkName> key=<AccessKey> keyUsage=persistent\nnetsh wlan start hostednetwork	0
21075052	21030218	DataTrigger based on value of cell in DataGrid bound to DataView	Binding="{Binding Row.Matched}"	0
4098440	4097067	double division by using two floats?	int count = 7;\ndouble value = 0.0073812398871474;\ndouble r = (double) (1.0f / count); // approximate reciprocal\nr = r * (2.0 - count*r); // much better approximation\nr = r * (2.0 - count*r); // should be full double precision by now.\ndouble result = value * r;	0
32234527	32234297	Index was outside bounds of array	System.IO.IOException: The process cannot access the file 'C:\test.jpg' because it is being used by another process.	0
4796225	4796109	How to move item in listBox up and down?	private void UpClick()\n{\n    // only if the first item isn't the current one\n    if(listBox1.ListIndex > 0)\n    {\n        // add a duplicate item up in the listbox\n        listBox1.AddItem(listBox1.Text, listBox1.ListIndex - 1);\n        // make it the current item\n        listBox1.ListIndex = (listBox1.ListIndex - 2);\n        // delete the old occurrence of this item\n        listBox1.RemoveItem(listBox1.ListIndex + 2);\n    }\n}\n\nprivate void DownClick()\n{\n   // only if the last item isn't the current one\n   if((listBox1.ListIndex != -1) && (listBox1.ListIndex < listBox1.ListCount - 1))\n   {\n      // add a duplicate item down in the listbox\n      listBox1.AddItem(listBox1.Text, listBox1.ListIndex + 2);\n      // make it the current item\n      listBox1.ListIndex = listBox1.ListIndex + 2;\n      // delete the old occurrence of this item\n      listBox1.RemoveItem(listBox1.ListIndex - 2);\n   }\n}	0
8139511	8139265	JSON.Net incorrectly serializes a two dimensional array to a one dimension	// output: [[1,1,1,1],[2,2,2,2]]\nvar a = new int[][] { new[]{ 1, 1, 1, 1 }, new[]{ 2, 2, 2, 2 } };	0
25481825	25481550	How to add TextField by pressing button in C# and WPF?	t[i] = new TextBox();\nt[i].Text = "new textbox";\nt[i].textBox2.Name = "textBox1";\n\nGrid1.Children.Add(t[i]);\n//or SomeStackPanel.Children.Add(t[i]);	0
11388647	11388607	Get key and value types of non-generic IDictionary at runtime	var dict = new System.Collections.Specialized.HybridDictionary();\n\ndict.Add(1, "thing");\ndict.Add("thing", 3);	0
1150036	1148875	Is it possible to set a command button to have a 3D disabled graphic in Visual Studio 2008?	using System;\nusing System.Drawing;\nusing System.Windows.Forms;\n\npublic class MyButton : Button {\n  protected override void OnSizeChanged(EventArgs e) {\n    base.OnSizeChanged(e);\n    Bitmap bmp = new Bitmap(this.Width, this.Height);\n    using (Graphics gr = Graphics.FromImage(bmp)) {\n      ButtonRenderer.DrawButton(gr,\n        new Rectangle(0, 0, bmp.Width, bmp.Height),\n        System.Windows.Forms.VisualStyles.PushButtonState.Normal);\n    }\n    if (this.BackgroundImage != null) this.BackgroundImage.Dispose();\n    this.BackgroundImage = bmp;\n  }\n}	0
16669581	16669386	Finding the column total in an array	for (int i = 0; i < totalRows; i++)\n{\n    for (int j = 0; j < totalColumns; j++)\n    {\n        rowTotal[i] += numbers[i * totalColumns + j];\n        blockTotal[j] += numbers[i * totalColumns + j];\n    }            \n}	0
7330139	7330111	Select Folder Path with savefileDialog	// Bring up a dialog to chose a folder path in which to open or save a file.\nprivate void folderMenuItem_Click(object sender, System.EventArgs e)\n{\n    // Show the FolderBrowserDialog.\n    DialogResult result = folderBrowserDialog1.ShowDialog();\n    if( result == DialogResult.OK )\n    {\n        folderName = folderBrowserDialog1.SelectedPath;\n        ... //Do your work here!\n    }\n}	0
3085380	3085345	String Format % with significant figures	{0:0.00%}	0
32273817	32273617	Parse JSON String into List<string>	void Main()\n{\n    string json = "{\"People\":[{\"FirstName\":\"Hans\",\"LastName\":\"Olo\"},{\"FirstName\":\"Jimmy\",\"LastName\":\"Crackedcorn\"}]}";\n\n    var result = JsonConvert.DeserializeObject<RootObject>(json);\n\n    var firstNames = result.People.Select (p => p.FirstName).ToList();\n    var lastNames = result.People.Select (p => p.LastName).ToList();\n}\n\npublic class Person\n{\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n}\n\npublic class RootObject\n{\n    public List<Person> People { get; set; }\n}	0
30570684	30569110	AccessViolationException occured using P/Invoke with Media Foundation Interface in Multithread application	backgroundThread.TrySetApartmentState(ApartmentState.STA); // Add this to fix createWMV() in multithreading\nbackgroundThread.Name = "CreateVideoThead";\nbackgroundThread.Start();	0
7656194	7656184	DateTimePicker Format	dtp_btime.Value.ToString("hh:mm tt")	0
20750156	20750144	How to render a Web User Control into a PlaceHolder	protected void button1_Click(object sender, EventArgs e)\n{\n   WebControlDemo wcd = this.LoadControl("~/SomePath/WebControlDemo.ascx") as WebControlDemo;\n   this.placeHolder1.Controls.Add(wcd);\n}	0
16581919	16579410	How to open image or pdf file in a new window?	//In Default2.aspx\nprotected void LinkButton1_Click(object sender, EventArgs e)\n    {\n       Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "Default3.aspx"));\n    }\n\n//------------\n//In Default3.aspx\n\nprotected void Page_Load(object sender, EventArgs e)\n    {\n        string path = Server.MapPath("~\\E:\\karthikeyan\\venky\\pdf\\aaaa.PDF");\n        WebClient client = new WebClient();\n        Byte[] buffer = client.DownloadData(path);\n        if (buffer != null)\n        {\n            Response.ContentType = "application/pdf";\n            Response.AddHeader("content-length", buffer.Length.ToString());\n            Response.BinaryWrite(buffer);\n        }\n    }	0
31246257	31246133	Get Selected Item ListBox WP8.1 C#	private async void EditButton_Click(object sender, RoutedEventArgs e)\n    {\n        WritePadFileContent listitem = (e.OriginalSource as MenuFlyoutItem).DataContext as WritePadFileContent;\n        MessageDialog messageDialog = new MessageDialog(listitem.Name.ToString());\n        await messageDialog.ShowAsync();\n\n\n\n        //code for export to pdf, it works\n    }	0
13690545	13690515	Fastest way to check if a always changing set of strings contains a string	HashSet<string> hs = new HashSet<string>();\nbool b1 = hs.Add("xxx"); //returns true\nbool b2 = hs.Add("xxx"); //returns false	0
18412718	18412516	char[] array to textfile, including non-printing control characters	static string Encr(string plainText, string key)\n{\n    char[] chars = new char[plainText.Length];\n    int h = 0;\n    for (int i = 0; i < plainText.Length; i++)\n    {\n        if (h == key.Length)\n            h = 0;\n        int j = plainText[i] + key[h];\n        chars[i] = (char)j;\n        h++;\n    }\n\n    File.WriteAllBytes(FILE_NAME, System.Text.Encoding.UTF8.GetBytes(chars));\n\n    return new String(chars, System.Text.Encoding.UTF8);\n}	0
14725857	14725578	Adding XML Documentation to a Function	/// <summary>\n/// \n/// </summary>\n/// <param name="nameEntities"></param>\n/// <param name="childID"></param>\n/// <returns></returns> <!--etc-->\nprivate delegate Nullable<int> ExtractParentIdDelegate(IEnumerable<int> nameEntities, int childID);\n\n/// <summary>\n/// \n/// </summary>\nprivate ExtractParentIdDelegate FuncExtractParentId\n{\n    get\n    {\n        return this._extractParentId = this._extractParentId ?? new ExtractParentIdDelegate(delegate(IEnumerable<int> nameEntites, int childID)\n                                                                    {\n                                                                            //\n                                                                    });\n    }\n}	0
5252772	5252690	How to move button in Thread	private void Go()\n{\n    while ((button1.Location.X + button1.Size.Width) < this.Size.Width)\n    {\n        Invoke(new moveBd(moveButton), button1);\n        Thread.Sleep(50);\n    }\n}	0
17987746	17987594	WPF - Binding to Public Fields	public class MetaPerson\n{\n    public Person Person { get; set; }\n    public String SomeMeta { get; set; }\n}	0
11013933	11013253	Compare the load/performance of two functions	var stopWatch = new Stopwatch();\n        stopWatch.Start();\n        var result = CallFunction();\n        stopWatch.Stop();\n        var executionTime = stopWatch.Elapsed;	0
12221139	12220942	How to open particular directory dialog box?	Process.Start(@"C:\Temp\");	0
13163109	13153767	Serializing Dictionary< String, Dictionary< String, String > > in any form (Json, xml etc.)	public String Serialize(Dictionary<int, Dictionary<String, String>> all)\n        {\n\n            String abc = JsonConvert.SerializeObject(all, Formatting.None, new JsonSerializerSettings\n                        {\n                            TypeNameHandling = TypeNameHandling.Objects,\n                            TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple\n                        });\n            return abc;\n        }\n\n         public Dictionary<int, Dictionary<String, String>> DeSerialize(String text)\n         {\n\n             Dictionary<int, Dictionary<String, String>> abc;\n             abc = JsonConvert.DeserializeObject<Dictionary<int, Dictionary<String, String>>>(text, new JsonSerializerSettings\n             {\n                 TypeNameHandling = TypeNameHandling.Objects,\n                 TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple,\n             });\n             return abc;\n         }	0
9922780	9922667	Use moq to mock a type with generic parameter	public interface IAggregateRoot { }\n\nclass Test : IAggregateRoot { }\n\npublic interface IRepository<T> where T : IAggregateRoot\n{\n    // ...\n    IList<T> FindAll();\n    void Add(T item);\n    // ...\n }\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        // create Mock\n        var m = new Moq.Mock<IRepository<Test>>();\n\n        // some examples\n        m.Setup(r => r.Add(Moq.It.IsAny<Test>()));\n        m.Setup(r => r.FindAll()).Returns(new List<Test>());\n        m.VerifyAll();\n    }\n}	0
17102930	17102784	Linq: determine if the number of items in a sequence meets a condition	MyEnumerable.Take(2).Count() == 1 //to check if it has one element	0
6274844	6274544	How to create multiple tree view in single treeview in winforms?	treeView1.BeginUpdate();\ntreeView1.ShowRootLines = false;\ntreeView1.ShowLines = false;\ntreeView1.Nodes.Add("Parent");\ntreeView1.Nodes[0].Nodes.Add("Child 1");\ntreeView1.Nodes[0].Nodes.Add("Child 2");\ntreeView1.Nodes[0].Nodes[1].Nodes.Add("Grandchild");\ntreeView1.Nodes[0].Nodes[1].Nodes[0].Nodes.Add("Great Grandchild");\ntreeView1.EndUpdate();	0
9298240	9297834	Getting the width of the left most column header (but it really isn't a real column header)	datagrid.RowHeadersWidth	0
26803428	26803056	C# Generate a lambda expression where return type is unknown in compile time	var call = Expression.Call(methodInfo, iParam);\nvar cast = Expression.Convert(call, typeof (Object));\nvar lambda = Expression.Lambda<Func<int, Object>>(cast, iParam);	0
17244709	17244501	Is there a way to make a cell editable where column is readonly in XtraGrid?	var grid = sender as GridView;\nif (grid.FocusedColumn.FieldName == "Value") {\n    var row = grid.GetRow(grid.FocusedRowHandle) as // your model;\n    // note that previous line should be different in case of for example a DataTable datasource\n    grid.ActiveEditor.Properties.ReadOnly = // your condition based on the current row object\n}	0
2974163	2973347	Using WDDCEDEEIWEB201to find associated timestamps from database	var issues = \n    from i in ReadOnlyContext.Issues\n    let startInside = (startDate < i.OutOfOrderStart && i.OutOfOrderStart < endDate)\n    let endInside = (startDate < i.OutOfOrderEnd && i.OutOfOrderStart < endDate)\n    let allOutside = (startDate > i.OutOfOrderEnd && endDate < i.OutOfOrderEnd)\n    where i.TruckID == truckID && (startInside || endInside || allOutside)\nselect i;	0
29222348	29222315	C# how to stop a program and its task completely	Environment.Exit(0)	0
25065246	25064920	Message box closes automatically after a brief delay	Dispatcher.BeginInvoke(\n    new Action(() => MessageBox.Show(this, e.Message)),\n    DispatcherPriority.ApplicationIdle\n);	0
16262374	16261997	capturing screen area without caret	[DllImport("User32",\n           CallingConvention = CallingConvention.Winapi,\n           ExactSpelling = true,\n           EntryPoint = "HideCaret",\n           SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nprivate static extern Boolean HideCaret(IntPtr hWnd);\n\n[DllImport("User32",\n           CallingConvention = CallingConvention.Winapi,\n           ExactSpelling = true,\n           EntryPoint = "ShowCaret",\n           SetLastError = true)]\n[return: MarshalAs(UnmanagedType.Bool)]\nprivate static extern Boolean ShowCaret(IntPtr hWnd);\n\n\n// If the window you have to copy is in your process then \n// handle = IntPtr.Zero\n// Otherwise your have to find it out via GetWindowThreadProcessId and GetGUIThreadInfo \n\nHideCaret(handle);\n\ntry {\n  // Your code to capture the image \n}\nfinally {\n  ShowCaret(handle);\n}	0
20947269	20947215	How to do "nothing" in the else part of ternary operator	IEnumerable<string> commonValues = projects.Intersect(sheetNames);	0
7775530	7774995	Limiting the number of simultaneously executing tasks	Parallel.Invoke(\n    new ParallelOptions() { MaxDegreeOfParallelism = 3 }, \n    () => DoSomething(), \n    () => DoSomething(),\n    () => DoSomething(),\n    () => DoSomething(),\n    () => DoSomething());	0
8300652	8300626	Replacing text in a string	result.Replace("\"\"", "\"null\"");	0
12721589	12720758	How to show relationship between two model in MVC?	public class CountryModel : BaseNopEntityModel,\n{\n    public string Name { get; set; }\n    public Regionmodel Region{get; set; }\n}	0
10846382	10846264	how to parse dd.mm.yyyy format RegularExpressionAttribute MVC'sDataAnnotations?	(0[1-9]|[12][0-9]|3[01])[\.](0[1-9]|1[012])[\.](19|20)[0-9]{2}	0
6396925	6396888	How to escape a loop	class Program\n    {\n        static void Main(string[] args)\n        {\n\n            while (true)\n            {\n                ChangeFiles();\n\n                bool changes = ScanChanges();\n\n                if (!changes) \n                {\n                    TrimFolder();\n\n                    TrimFile();\n                }\n                Thread.Sleep(10000);\n            }\n        }\n\n\nprivate static void ChangeFiles()\n{\n  // code here\n}\n\nprivate static bool ScanChanges()\n{\n     FileInfo fi = new FileInfo("input.txt");\n     if (fi.Length > 0)\n     {\n         return true;\n     }\n     else\n     {\n         Process.Start("cmd.exe", @"/c test.exe -f input.txt > output.txt").WaitForExit();\n\n         return false;\n      }      \n}	0
9589754	9589635	asp.net inserting data into SQL Server db in while loop	while (ctecka.Read())\n{\n    exJmeno = ctecka[0].ToString();\n    exPrijmeni = ctecka[1].ToString();\n    Response.Write(exJmeno + " " + exPrijmeni + " ");\n    vlozSQL.Parameters.Clear();\n    vlozSQL.Parameters.AddWithValue("@name", exJmeno);\n    vlozSQL.Parameters.AddWithValue("@surname", exPrijmeni);\n    pridano = vlozSQL.ExecuteNonQuery();\n}	0
24571987	24566694	How to Insert values to strongly typed DataSet from code and then show it from RDLC reporting page?	ReportDataSource datasource = new ReportDataSource("TableName", ds.Tables[0]);\nReportViewer1.LocalReport.DataSources.Clear();\nReportViewer1.LocalReport.DataSources.Add(datasource);	0
22456852	22454194	font size affecting size of Label	private void Form1_Resize(object sender, EventArgs e)\n    {\n\n        Font f;\n        Graphics g;\n        SizeF s;\n        Single Faktor, FaktorX, FaktorY;\n\n        g = label2.CreateGraphics();\n        s = g.MeasureString(label2.Text, label2.Font, label2.Size);\n        g.Dispose();\n\n        FaktorX = label2.Width / s.Width;\n        FaktorY = label2.Height / s.Height;\n\n        if (FaktorX > FaktorY)\n        {\n            Faktor = FaktorY;\n        }\n        else\n        {\n            Faktor = FaktorX;\n        }\n\n        f = label2.Font;\n        label2.Font = new Font(f.Name, f.SizeInPoints * Faktor);\n    }	0
27027157	27027101	Regex - match digits after first three	(?<=;20)\d+	0
4674943	4619829	implementing a read/write field for an interface that only defines read	public override DateTime StartTime\n{\n    get { return start_time_; }\n}\n\ninternal void SetStartTime\n{\n    start_time_ = value;\n}	0
27087927	27082417	Value Converter for Binding Images in ListView for Windows Store App	public class ImageFileConverter : IValueConverter\n{\n    public object Convert(object value, Type targetType, object parameter, string language)\n    {\n        string fileName = value as string;\n\n        if (fileName != null)\n        {\n            BitmapImage bitmap = new BitmapImage();\n            bitmap.UriSource = new Uri("ms-appdata:///local/" + fileName);\n            return bitmap;\n        }\n        return null;\n    }\n    public object ConvertBack(object value, Type targetType, object parameter, string language)\n    {\n        throw new NotImplementedException();\n    }\n}	0
17219075	17186967	Linq2Twitter how to get retweeters	var status =\n            (from tweet in twitterCtx.Status\n             where tweet.Type == StatusType.Retweeters &&\n                   tweet.ID == "210591841312190464"\n             select tweet)\n            .SingleOrDefault();\n\n        status.Users.ForEach(\n            userID => Console.WriteLine("User ID: " + userID));	0
10355357	10354895	How to test a VS C# program on another computer	copy "C:\Documents and Settings\user123\Desktop\eFormsSystem\eFormsApp\bin\Debug\*.*" s:\debug\ /Z /Y	0
27587920	27587776	ImapX can't login to local hMailServer from my application, but Thunderbird can	String.Trim	0
854003	853990	Is there an easy way to append lambdas and reuse the lambda name in order to create my Linq where condition?	var tempFunc = func;\nfunc = a => tempFunc(a) && ...	0
3013852	3013833	check existense between two IEnumerable	int[] id1 = { 44, 26, 92, 30, 71, 38 };\n int[] id2 = { 39, 59, 83, 47, 26, 4, 30 };\n\n IEnumerable<int> both = id1.Intersect(id2);\n\n foreach (int id in both)\n     Console.WriteLine(id);\n\n //Console.WriteLine((both.Count() > 0).ToString());\n Console.WriteLine(both.Any().ToString());	0
6968719	6964802	Add Static Item to Drop-down Programmatically LINQ	var LNQ = new LNQDataContext();\n\n    var quo = LNQ.tbl_job_quotas.Where(c => c.job_quota_job_number == _fJ).Select(c => new { ID = c.job_quota_ID, DESC = c.job_quota_ID + " | " + c.job_quota_desc });\n    var DtQu = new DataTable();\n    DtQu.Columns.Add("ID");\n    DtQu.Columns.Add("DESC");\n\n    DataRow drs;\n    drs = DtQu.NewRow();\n    drs[0] = "%%";\n    drs[1] = "ALL";\n    DtQu.Rows.Add(drs);\n\n    foreach (var a in quo)\n    {\n        drs = DtQu.NewRow();\n        drs[0] = a.ID;\n        drs[1] = a.DESC;\n        DtQu.Rows.Add(drs);\n    }\n\n    _ddActQuota.DataTextField = "DESC";\n    _ddActQuota.DataValueField = "ID";\n\n    _ddActQuota.DataSource = DtQu;\n    _ddActQuota.DataBind();	0
19571755	19560446	Display image depend on file type in Repeater Control	protected void Repeater1_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n    // Execute the following logic for Items and Alternating Items.\n    if (e.Item.ItemType == ListItemType.Item ||\n        e.Item.ItemType == ListItemType.AlternatingItem)\n    {\n        if (((DataRowView)e.Item.DataItem).Row["Type"].ToString() == "D")\n        {\n            ((Label)e.Item.FindControl("imagelabel")).Text = "<img src='/folder.png'>";\n        }\n        else\n        {\n            ((Label)e.Item.FindControl("imagelabel")).Text = "<img src='/file.png'>";\n        }\n    }\n}	0
33982839	33982620	Play animation with Xbox controller	const float threshold = 0.05;\nconst string axis = "LeftJoystickX";\nif (Input.GetAxis(axis) < -threshold)\n{\n  //go left\n} \nelse if (Input.GetAxis(axis) > threshold) \n{\n   //go right\n} \nelse \n{\n   // don't move\n}	0
3693464	3693343	resize groupbox with sleep between iteration show up after loop ends	groupBox1.Refresh();	0
19832937	19832560	Without Alter Command, Delete Cascade Rows	string deleteStuff = @"\n  DELETE FROM [ProductsImages] WHERE ProductId = @ProductId;\n  DELETE FROM [Products] WHERE ProductId = @ProductId;"\ndb.ExecuteNonQuery(deleteStuff);	0
6016463	6016392	Get generic parameters from a ByReferenceType with Mono.Cecil	ParameterDefinition parameter = ...;\nByReferenceType byref = (ByReferenceType) parameter.ParameterType;\nGenericInstanceType action_string = (GenericInstanceType) byref.ElementType;\nTypeReference action = action_string.ElementType;\nTypeReference str = action_string.GenericArguments [0];	0
24335733	24319411	Loop over a FormCollection to get radiobutton SelectedAnswers	for (int i = 0; i < 15; i++)\n  {\n     long x = Int64.Parse(form[String.Format("Questions[{0}].ObjectId", i)]);\n     long y = Int64.Parse(form[String.Format("Questions[{0}].SelectedAnswer", i)]);\n  if (x > 0 && y > 0)\n   {\n     selectedAnswers.Add(new SelectedAnswer() { questionId = x, answerId = y });\n   }\n }	0
1349319	1349306	How can i add new panel at run time in asp.net	//MyControl = Custom User Control\nvar myControl =  (MyControl) Page.LoadControl("MyControl.ascx"); \nthis.ControlContainer.Controls.Add(myControl);	0
9274296	9257314	Designing a data-driven logic system	rules = SELECT * FROM item_rules\nforeach(rules as _rule)\n{\n   count = SELECT COUNT(*) FROM (_rule[select_statement]) as T1\n   if(count > 1) itemlist.add(_rule[item_that_satisfy_rule])\n}	0
28968530	28968077	Is there any easer way to wipe all fixed sizes set for html nodes than I trying to code?	private static string RemoveHeightsAndWidths(string original)\n{\n    XElement element = XElement.Parse(original);\n    var tableRelatedElements =\n        element.Descendants("table")\n        .Union(element.Descendants("tr"))\n        .Union(element.Descendants("td"))\n        .Union(element.Descendants("th")); //add more items you want to strip the height and width from in the same manner\n\n    Regex reg = new Regex("(?:width:.*?;)|(?:height:.*?;)");\n\n    foreach (var item in tableRelatedElements)\n    {\n        if (item.Attributes("style").Any())\n        {\n            item.Attribute("style").Value = reg.Replace(item.Attribute("style").Value, string.Empty);\n        }\n        if (item.Attributes("height").Any())\n        {\n            item.Attribute("height").Remove();\n        }\n        if (item.Attributes("width").Any())\n        {\n            item.Attribute("width").Remove();\n        }\n    }\n\n    return element.ToString();\n}	0
2364987	2193831	Multiple Applications, Shared Settings: Use the registry or XML-based configuration?	string ponySetting = myRegistryObject["DefaultPonySetting"]	0
6686998	6686342	programmatic password recovery from access 2007	Debug.Print CurrentDb.TableDefs("YourTableLink").Connect	0
8220753	8220654	Quickest way to get distinct lists using linq/lambdas	// linq expression\nvar dist = from d in dictionaries\n           group d by new { WAP = d["WAP"], System = d["System"] } into g\n           select g.FirstOrDefault();\n\n//lambdas\nvar dist = dictionaries\n              .GroupBy(d => new { WAP = d["WAP"], System = d["System"] })\n              .Select(g => g.FirstOrDefault())	0
15140148	15140038	Display all elements in array from a response	foreach(var customer in _response.Customers)\n{\n    Console.WriteLine(customer.CustID);\n}	0
27626816	27605138	How to create same MD5 token in different platforms?	func doSha256(#dataIn:NSData) -> NSData {\n    var shaOut: NSMutableData! = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH));\n    CC_SHA256(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(shaOut.mutableBytes));\n\n    return shaOut;\n}	0
5238710	5237449	Refactor to Design Patterns: applying adapter pattern to 3rd party API	public IList<MyCustomerObjects> GetCustomers()\n{\n    //Call out to the third party API with the appropriate filters\n\n    //foreach object in 3rd party collection, wrap in adapter class and add to list\n\n    //return list of your objects\n}	0
22664270	22664003	How to order data with matching ID from another table using linq?	from t1 in TABLE1\njoin t2 in TABLE2 on t1.COL_B equals t2.COL_A\norderby t2.COL_B\nselect t1	0
4884235	4884214	Object reference null for the same statement in asp.net	StudentInfo sInfo = new StudentInfo ();	0
19067882	19067617	Edit richtextbox to keep only words that contains underscore	var text = @"Release to user USER the roles: ZBR_POA_FIL_APOIO_GESTAO, ZBR_REC_FIL_SUPPORT, ZBR_RJO_CD_FIL_SUPPORT, ZBR_SVD_CD_FIL_SUPPORT, Z_GENERAL_OBJECTS, Z_DEBUG, Z_CHECK";\nvar words = text.Split(new[] { ' ', ',' }, StringSplitOptions.RemoveEmptyEntries);\nvar wordsWithUnderscores = words.Where(o => o.Contains("_")).ToArray();\n\nforeach(var word in wordsWithUnderscores) {\n    Console.WriteLine(word);\n}	0
5675099	5674971	app.config for a class library	app.config	0
30473842	30462988	Colour a cell in datagridview	private void dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n        {\n            DataGridViewCellStyle MakeItRed = new DataGridViewCellStyle();\nMakeItRed.BackColor = Color.Red;\n\n//make a whole column red\ndataGridView1.Columns[1].DefaultCellStyle = MakeItRed;\n\n//make a specific cell red\nDataGridViewRow row2 = dataGridView1.Rows[2];\nrow2.Cells[2].Style = MakeItRed;\n\n        }	0
28869814	28858337	How to insert custom page number in Aspose.Words	String src = dataDir + "Page numbers.docx";\nString dst = dataDir + "Page numbers_out.docx";\n\n// Create a new document or load from disk\nAspose.Words.Document doc = new Aspose.Words.Document(src);\n// Create a document builder\nAspose.Words.DocumentBuilder builder = new DocumentBuilder(doc);\n// Go to the primary footer\nbuilder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);\n// Add fields for current page number\nbuilder.InsertField("PAGE", "");\n// Add any custom text\nbuilder.Write(" / ");\n// Add field for total page numbers in document\nbuilder.InsertField("NUMPAGES", "");\n\n// Import new document\nAspose.Words.Document newDoc = new Aspose.Words.Document(dataDir + "new.docx");\n// Link the header/footer of first section to previous document\nnewDoc.FirstSection.HeadersFooters.LinkToPrevious(true);\ndoc.AppendDocument(newDoc, ImportFormatMode.UseDestinationStyles);\n// Save the document\ndoc.Save(dst);	0
2375244	2375191	Recurse through properties of a class	/// <summary>This Method Does Something</summary>\n/// <BugFix BugId="1234" Programmer="Bob" Date="2/1/2010">Fix Comments</BugFix>\npublic void MyMethod()\n{\n    // Do Something\n}	0
2361105	2360992	Binding a datasource to a rdl in report server programmatically - SSRS	ReportParameter[] Params = new ReportParameter[1];\nParams[0] = "Parameter Value";\nReportViewerControl.ServerReport.SetParameters(Params);	0
11331900	11331575	Mapping a private backing field with MongoDB C#	BsonClassMap.RegisterClassMap<Competitor>(cm =>\n{\n    cm.AutoMap();\n    cm.MapField("_competitorBests").SetElementName("CompetitorBests");\n});	0
2956951	2956829	Managing Lots of Overlapping Controls in Visual Studio	userControl.Visible = false	0
16337992	16337762	Assigning blank value to a DateTime filed	static DateTime? TestDate(string date)\n    {\n        DateTime result;\n        if (DateTime.TryParse("", out result))\n        {\n            return result;\n        }\n        return null;\n    }	0
5463698	5463469	Storing Datasets in a RESX file	using (Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("ConsoleApplication1.MyFile.MyExt"))\n{\n   // load data from stream\n}	0
12128317	12128130	List XML Serialization Doubling Elements	TestSerializer copy = x.Deserialize(stream) as TestSerializer;	0
28922194	28920768	How to seed identity seed value in entity framework code first for several tables	internal class DefaultMigrationSqlGenerator : SqlServerMigrationSqlGenerator\n    {\n        protected override void Generate(AlterTableOperation alterTableOperation)\n        {\n            base.Generate(alterTableOperation);\n            // If the tables you want to reseed have an Id primary key...\n            if (alterTableOperation.Columns.Any(c => c.Name == "Id"))\n            {\n                string sqlSeedReset = string.Format("DBCC CHECKIDENT ({0}, RESEED, 1000) ", alterTableOperation.Name.Replace("dbo.", ""));\n\n                base.Generate(new SqlOperation(sqlSeedReset));\n            }\n        }\n    }	0
3191000	3190960	Traverse ftp subfolders to get file sizes in C#	WebRequestMethods.Ftp.ListDirectory	0
4226692	4226657	trim string at the end of the string	var query = "SELECT * FROM People WHERE City = @City AND County = @County AND";\nvar scrubbed = query.Substring(0, query.Length - 4);	0
7446863	7445852	Unable to get preloaded assembly with Assembly.Load()	public static Assembly GetAssemblyFromAppDomain(string assemblyName)\n{\n    foreach (var assembly in AppDomain.CurrentDomain.GetAssemblies())\n    {\n        if (assembly.FullName.StartsWith(assemblyName + ",")) \n        {\n            return assembly;\n        }\n    }\n    return null;   \n}	0
18435725	18435711	How to find data using using primary key in Entity Framework?	tabCom com = db.tabCom.Single(tab => tab.PrimaryKeyColumn == 3);	0
26065125	26064903	How to assign a time value from a textbox to a variable?	DateTime dt = DateTime.ParseExact(time.Replace(": ", ":").Replace(" :", ":"), "HH:mm:ss:fff", CultureInfo.InvariantCulture);	0
29393862	29393332	How to handle a NULL value in reader.GetByte(x)?	//Check to see if the Unique_ID is 10 or 11 and process accordingly\n//10 = Both boxes, 11 = Rework only\nif (reader.IsDBNull(16))\n{\n   //Add here your code to handle null value\n}\nelse\n{\n   //Use a switch to read the value only one time\n   switch (reader.GetByte(16))\n   {\n     case 10:\n       int ES = Convert.ToInt32(reader["ESCALATED"]);\n       if (ES == 0)\n       {\n          chkEscalated.Checked = false;\n       }\n       else\n       {\n          chkEscalated.Checked = true;\n          chkEscalated.Visible = true;\n          lblEscalated.Visible = true;\n          chkRework.Visible = true;\n          lblRework.Visible = true;\n        }\n        break;\n\n      case 11:\n        break;\n\n      default:\n        break;\n   }\n}	0
14854250	14853916	Nhibernate mapping, cascade, inverse, update, insert?	session.Evict(employeeMonth.BonusMonth)	0
1463391	1458748	WPF: OnKeyDown() not being called for space key in control derived from WPF TextBox	public class SelectableTextBlock : TextBox\n{\n    public SelectableTextBlock() : base()\n    {\n        this.AddHandler(SelectableTextBlock.KeyDownEvent, new RoutedEventHandler(HandleHandledKeyDown), true);\n    }\n\n    public void HandleHandledKeyDown(object sender, RoutedEventArgs e)\n    {\n        KeyEventArgs ke = e as KeyEventArgs;\n        if (ke.Key == Key.Space)\n        {\n            ke.Handled = false;\n        }\n    }\n    ...\n}	0
18749992	18749446	How can I get a data source's value from a data binding?	Binding bind = (sender as Control).DataBindings[0];\nDataTable table = (bind.DataSource as DataSet).Tables[0];\nstring table_column_name = bind.BindingMemberInfo.BindingMember;\nstring column_name = table_column_name.Split(new char[] { '.' })[1];\nDataColumn column = table.Columns[table.Columns.IndexOf(column_name)];\nobject data = table.Rows[0][column];	0
19341811	19341752	Regex in c# for allowing numbers and alphabets	\d{9}[a-zA-Z]?[a-zA-Z0-9]?\d{0,3}	0
3649927	3649900	Making a .NET library in Visual Studio	MyCompany.Common	0
443507	443466	Lambda variable names - to short name, or not to short name?	myCollection.Where(person =>....); //non descriptive collection name\n\nmyPeopleCollection.Where(p=>...); // descriptive collection name	0
29470003	29368800	Column Boundaries getting overlapped in Telerik Grid for Winforms	private void RadGridView1_SizeChanged(object sender, EventArgs e)\n  {\n      radGridView1.TableElement.ViewElement.UpdateRows(true);\n  }	0
19894658	19894639	How to represent a 4 bit binary number with 8 bits in C#?	Convert.ToString(number, 2).PadLeft(8, '0');	0
14734456	14734348	Use Linq query to count grandchild elements that match conditions	var count = Model.Project.ProjectDoc\n   .Where(a => a.Current == true \n            && a.DocType == "Cover"\n            && a.ProjectDocVote.Any(v => v.UserID == ViewBag.CurrentUserID))\n   .Count():	0
727488	715626	Validating xml nodes, not the entire document	private void ValidateSubnode(XmlNode node, XmlSchema schema)\n{\n    XmlTextReader reader = new XmlTextReader(node.OuterXml, XmlNodeType.Element, null);\n\n    XmlReaderSettings settings = new XmlReaderSettings();\n    settings.ConformanceLevel = ConformanceLevel.Fragment;\n    settings.Schemas.Add(schema);\n    settings.ValidationType = ValidationType.Schema;\n    settings.ValidationEventHandler += new ValidationEventHandler(XSDValidationEventHandler);\n\n    using (XmlReader validationReader = XmlReader.Create(reader, settings))\n    {     \n        while (validationReader.Read())\n        {\n        }\n    }\n}\n\nprivate void XSDValidationEventHandler(object sender, ValidationEventArgs args)\n{\n    errors.AppendFormat("XSD - Severity {0} - {1}", \n                        args.Severity.ToString(), args.Message);\n}	0
9307844	9305685	How to use batching, something like BeginUpdate/EndUpdate, when doing bulk change in ViewModel in MVVM?	class BatchObservableColleciton<T> : INotifyCollectionChanged, IEnumerable\n{\n    public event NotifyCollectionChangedEventHandler CollectionChanged;\n\n    private List<T> _list;\n    private List<T> _addedItems;\n\n    public BatchObservableColleciton( ) {\n        _list = new List<T>( );\n        _addedItems = new List<T>( );\n    }\n\n    public IEnumerator GetEnumerator( )\n    {\n        return _list.GetEnumerator( );\n    }\n\n    public void Add( T item )\n    {\n        _list.Add( item );\n        _addedItems.Add( item );\n    }\n\n    public void commit( ) {\n        if( CollectionChanged != null ) {\n            CollectionChanged( this, new NotifyCollectionChangedEventArgs(\n                NotifyCollectionChangedAction.Add, _addedItems ) );\n        }\n        _addedItems.Clear( );\n    }\n\n}	0
19977351	19977142	How to navigate data from page to page?	NavigationService.Navigate(new Uri("/Organization_Details.xaml?selectedItem=" +Organization.Name , UriKind.Relative));	0
4891467	4889092	Accessing image resources from a loaded assembly	"pack://application:,,,/<PutHereAssemblyName>;component/" + path.TrimStart('/')	0
7883926	7883831	Send unicode String from C# to Java	void SendString(String message)\n{\n    byte[] buffer = Encoding.UTF8.GetBytes(message);\n    AsyncCallback ac = new AsyncCallback(SendStreamMsg);\n    tcpClient.GetStream().BeginWrite(buffer, 0, buffer.Length, ac, null);\n}	0
13398285	13397153	Runtime property override in order to fetch historical data	public class Foo {\n    public bool HistoricalMode { get; set; }\n\n    private string _property1;\n    public string Property1 { \n        get { \n            if (HistoricalMode) {\n                return GetHistoricalValue("Property1");\n            } else {\n                return _property1;\n            }\n        set {\n            if (HistoricalMode){\n                throw new NotSupportedException("Updates not possible in historical mode.");\n            } else {\n                _property1 = value;\n            }\n        }\n    }\n    public DateTime CreatedDate { \n        get {\n            // Similar pattern as above\n        }\n        set {\n            // Similar pattern as above\n        }\n    }\n\n    public string GetHistoricalValue(string propertyName) {\n        HistoryHelper historyHelper = CreateHistoryHelper(this);\n        return historyHelper.GetHistoricalValue(propertyName, CreatedDate);\n    }\n}	0
9216298	9216064	Connect to Outlook calendar from C# using Interop	Outlook.Application msOutlook = new Outlook.Application();\nOutlook.NameSpace session = msOutlook.Session;\nOutlook.Stores stores = session.Stores;\nforeach (Outlook.Store store in stores)\n{\n    Outlook.MAPIFolder folder = store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderCalendar);\n\n    MessageBox.Show(folder.Name);\n}	0
8535481	8535423	Execute any method by string with parameters	TestPlugin plugIn = new TestPlugin();\nobject[] params = null //... set parameters here\nMethodInfo mi = typeof(TestPlugin).GetMethod("Test");\nmi.invoke(plugIn,params);	0
4452006	1494857	RichTextBox Control in a Multi-Threaded Application	[ThreadStatic]\nstatic RichTextBox m_RtfConverter;\npublic static RichTextBox ThreadSafeRTFConverter {\n    get {\n        if(m_RtfConverter == null) {\n            m_RtfConverter = new RichTextBox();\n            m_RtfConverter.Width = 760;\n        }\n        return m_RtfConverter;\n    }\n}	0
18551117	18551104	How to apply Generics methods	public DateTime ExportResultsToCsv<T>(string filePath, string HeaderLine, List<T> data)   \n{\n    engine = new FileHelperEngine(typeof(T)) { HeaderText = HeaderLine };\n    engine.WriteFile(filePath, data);\n    return DateTime.Now;   \n}	0
27475198	27474976	Deserialize JSON attribute to class	public class HttpTest\n{\n    public bool ignoreCertificateErrors { get; set; }\n    public List<HttpStatusCode> successHTTPStatusCodes { get; set; }\n    public string httpVerb { get; set; }\n    public HttpMethod HttpMethodInstance { \n        get { return new HttpMethod(httpVerb); }\n    }\n}	0
4088098	4088064	Add OrderByDescending to Linq statement	.Select(...whatever...).OrderByDescending(item => item.count);	0
4213958	4213918	How can I create a 'power options' shortcut on desktop with C# code?	WshShell shell = new WshShell();\n        string app = Path.Combine(Environment.SystemDirectory, "powercfg.cpl");\n        string linkPath = @"C:\PowerLink.lnk";\n        IWshShortcut link = (IWshRuntimeLibrary.IWshShortcut)shell.CreateShortcut(linkPath);\n        link.TargetPath = app;\n        link.IconLocation = string.Format("{0},2", app);\n        link.Save();	0
12215879	12215224	Set File access rule	accessdeny.SetAccessRule(\n   new System.Security.AccessControl.FileSystemAccessRule(\n   new SecurityIdentifier(WellKnownSidType.WorldSid, null),\n   System.Security.AccessControl.FileSystemRights.FullControl,\n   System.Security.AccessControl.AccessControlType.Deny));	0
23299011	23298895	Lambda: efficiently find, modify, then group elements	var avg = pageHitList.GroupBy(x => x.RequestTime.RoundUp(TimeSpan.FromMinutes(30)));\n                     .Select(hit => new { \n                                 hit.Key, \n                                 Average = hit.Average(x => x.PageResponseTime) \n                             });	0
1059770	1059696	C# - Can a timer call a menu event?	private void createMenuItem_Click(object sender, EventArgs e)\n{\n  DoCanvasWork(); // pick a good name :)        \n}\n\nprivate void transfer_timer() {\n  System.Timers.Timer Clock = new System.Timers.Timer();\n  Clock.Elapsed += new ElapsedEventHandler(Clock_Tick);\n  Clock.Interval = timer_interval;  Clock.Start(); \n}\n\nprivate void Clock_Tick( object sender, EventArgs e )\n{\n  BeginInvoke( new MethodInvoker(DoCanvasWork) );\n}\n\nprivate void DoCanvasWork()\n{\n  canvas.Layer.RemoveAllChildren();\n  canvas.Controls.Clear();\n  createDock();\n}	0
3984636	3984590	download multiple files as zip in .net	Response.AddHeader("Content-Disposition", "attachment; filename=" + compressedFileName + ".zip");\nResponse.ContentType = "application/zip";\n\nusing (var zipStream = new ZipOutputStream(Response.OutputStream))\n{\n    foreach (string filePath in filePaths)\n    {\n        byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);\n\n        var fileEntry = new ZipEntry(Path.GetFileName(filePath))\n        {\n            Size = fileBytes.Length\n        };\n\n        zipStream.PutNextEntry(fileEntry);\n        zipStream.Write(fileBytes, 0, fileBytes.Length);\n    }\n\n    zipStream.Flush();\n    zipStream.Close();\n}	0
6156824	6156767	Enforcing type of attribute parameter	public class MyAttribute: Attribute \n    {\n        private Type _ClassType;\n        public MyAttribute(Type classType)\n        {\n            _ClassType = classType;\n        }\n        public void SomeMethod<T>() where T: IMyInterface\n        {\n            var expectedType = Activator.CreateInstance(typeof(T)) as IMyInterface;\n        // Do something with expectedType\n        }\n    }	0
4524135	4524070	How to zip a folder recursively?	ZipFile.AddDirectory	0
14960466	14960392	How to Delete the last line of a file.txt	var lines = File.ReadAllLines(pathToFile);\nFile.WriteAllLines(pathToFile, lines.Take(lines.Length - 1));	0
30765130	30765061	Find All Rows in DataTable Where Column Value is NOT Unique Using Linq Query	(from r in dt.AsEnumerable()\ngroup r by r.TxnNumber into grp\nwhere grp.Count() > 1\nselect grp).SelectMany(x=>x).ToList();	0
10362609	10362130	How to find the available EnvDTE.Comands names for Visual Stuadio 2010?	private void EnumerateCommads()\n{\n    foreach (Command command in _applicationObject.Commands)\n    {\n        //print command\n    }\n}	0
23652324	23651827	How to insert data into sql server within a foreach loop in c#	CREATE PROC Createciudad(@nombre        VARCHAR(50), \n                     @codigo_postal VARCHAR(50))	0
9297089	9296976	How do I make it so that when I have a specific Key press it creates an interupt	private void YourControl_KeyDown(object sender, System.Windows.Forms.KeyEventArgs e)\n{\n    if (e.KeyCode == Keys.NumPad0) \n    {\n       //Grab mouse coordinates\n    }\n    if (e.KeyCode == Keys.NumPad1) \n    {\n       //Code to move the mouse\n    }\n}	0
21035846	21014570	Getting my array[1] to get values from another array	public class Skill {\n    //....variables\n}    \n\npublic List<Skill> allSkills    = new List<Skill>();\npublic Skill[] skillArray;\n\nvoid GetArray ()\n{\n   string blah = PlayerPrefs.GetString("CatSkills");\n   JsonConvert.DeserializeObject<List<Skill>>(blah).CopyTo(skillArray, 0);\n}	0
19840331	19839800	How to print a text file using C#	System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo(@"C:\temp\output.txt");\npsi.Verb = "PRINT";\n\nProcess.Start(psi);	0
31979122	29446753	Perform Dougman't Method (Rubber Sheet Model) in Emgu CV	// Fungsi untuk merubah bentuk donnut menjadi lembaran\n        public Image<Gray, Byte> dougman(Image<Gray,Byte> cit, Double radiris) \n        {\n            double xP, yP, r, theta;\n            Image<Gray, Byte> grayT = new Image<Gray, Byte>(360, 116);\n\n            for (int i = 0; i < 116; i++)\n            {\n                for (int j = 0; j < 360; j++)\n                {\n                    r = i;\n                    theta = 2.0 * Math.PI * j / 360;\n                    xP = r * Math.Cos(theta);\n                    yP = r * Math.Sin(theta);\n                    xP = xP + radiris + 10; //sekitar 115\n                    yP = yP + radiris + 10;\n                    grayT[116 - 1- i, j] = cit[(int)xP, (int)yP];\n                }\n            }\n            return grayT;\n        }	0
2623400	2603380	How to create a route that catch all pdf file?	string FilePath = MapPath("your.pdf");\nResponse.ContentType = "Application/pdf";\nResponse.AppendHeader( "content-disposition", "attachment; filename=" + FilePath);\nResponse.WriteFile(FilePath);\nResponse.End();	0
14075336	14075299	String split algorithm	var inputString = "Word1 Word2 Word3 Word4 Word5 Word6 Word7 Word8" ;\nvar separators = new []{"word2", "word7, "word4"};\nvar output = inputString.Split(seperators,StringSplitOptions.None);	0
1542392	1433638	how to add event listener via fluent nhibernate?	_sessionFactory = Fluently.Configure()\n   .Database(MsSqlConfiguration.MsSql2005.ConnectionString(connectionString).ShowSql())\n   .Mappings(m => m.FluentMappings.AddFromAssemblyOf<Entity>())\n   .ExposeConfiguration(c => c.EventListeners.PreUpdateEventListeners = new IPreUpdateEventListener[] {new AuditEventListener()});	0
32511939	32489836	Radio button/checkbox array not displaying saved values	public Response(int id, int qID)\n            {\n                this.ResponseBool = new ResponseRepository().GetResponse(id).Where(m => m.QuestionID == qID).Select(m => m.ResponseBool).FirstOrDefault();\n    }\n\n      Answers = Questions\n                     .Select(k => new Response(stepOneSaved.ApplicationID, k.QuestionID)\n                    {\n                        ApplicationID = stepOneSaved.ApplicationID,\n                        QuestionID = k.QuestionID,\n                        QuestionCategoryID = k.QuestionCategoryID,\n                        QuestionText = k.QuestionText,\n                    })\n                    .ToList();	0
7383407	7367121	How to distinguish between usb-serial converters?	var guidComPorts = Guid.Empty;\n        UInt32 dwSize;\n        IntPtr hDeviceInfo;\n        var buffer = new byte[512];\n        var providerName = new[] { };\n        var spddDeviceInfo = new SpDevinfoData();\n        var bStatus = SetupDiClassGuidsFromName("Ports", ref guidComPorts, 1, out dwSize);\n        if (bStatus)\n        {\n            hDeviceInfo = SetupDiGetClassDevs(\n                ref guidComPorts,\n                (IntPtr)null,\n                (IntPtr)null,\n                DigcfPresent | DigcfProfile);\n            if (hDeviceInfo.ToInt32() != 0)\n            {\n\n                while (true)\n                {\n                    spddDeviceInfo.CbSize = Marshal.SizeOf(spddDeviceInfo);// IS IT THIS LINE WORK FOR 64 BIT                        \n                    bStatus = SetupDiEnumDeviceInfo(hDeviceInfo, nDevice++, ref spddDeviceInfo);\n                    break;\n                }\n\n            }\n\n\n            return;\n        }\n\n    }	0
15783088	15782857	Displaying an icon in a picturebox	pictureBox1.Image = Bitmap.FromHicon(new Icon(openFileDialog.FileName, new Size(48, 48)).Handle);	0
6298809	6298763	How do I write an extension function to return the average of a custom type?	static class DataPointExtensions\n{\n public static DataPoint Average (this IEnumerable<DataPoint> points)\n {\n   int sumX=0, sumY=0, sumZ=0, count=0;\n   foreach (var pt in points)\n   {\n      sumX += pt.X;\n      sumY += pt.Y;\n      sumZ += pt.Z;\n      count++;\n   }\n   // also calc average time?\n   if (count == 0)\n     return new DataPoint ();\n   return new DataPoint {X=sumX/count,Y=sumY/count,Z=sumZ/count};\n }\n}	0
2669742	2669610	How to merge two didctionaries in C# with duplicates	Dictionary<string, string[]> firstDic = new Dictionary<string, string[]>  \n{  \n    {"apple", new [] {"red"}},  \n    {"orange", new [] {"orange"}}  \n};\n\nDictionary<string, string[]> secondDic = new Dictionary<string, string[]>\n{\n    {"apple", new [] {"green"}},\n    {"banana", new [] {"yellow"}}\n};\n\nDictionary<string, string[]> resultDic = firstDic.Union(secondDic).GroupBy(o => o.Key).ToDictionary(o => o.Key, o => o.SelectMany(kvp => kvp.Value).ToArray());	0
15415960	15415881	Define resources in C# instead of xaml	var model = this.Resources["Model] as PeopleViewModel;	0
15855442	15853991	Pass context to collection validators in FluentValidation with MVC integration	public class FooValidator : AbstractValidator<Foo>, IValidatorInterceptor   \n{\n\n    public FooValidator() { }\n\n    public ValidationContext BeforeMvcValidation(ControllerContext controllerContext, ValidationContext validationContext)\n    {\n        RuleFor(f => f.Bar).SetCollectionValidator(new BarValidator(validationContext.InstanceToValidate as Foo));\n\n        return validationContext;\n    }\n\n    public ValidationResult AfterMvcValidation(ControllerContext controllerContext, ValidationContext validationContext, ValidationResult result)\n    {\n        return result;\n    }\n}	0
24367618	24367571	Insert string into a filepath string before the file extension C#	string AddSuffix(string filename, string suffix)\n{\n    string fDir = Path.GetDirectoryName(filename);\n    string fName = Path.GetFileNameWithoutExtension(filename);\n    string fExt = Path.GetExtension(filename);\n    return Path.Combine(fDir, String.Concat(fName, suffix, fExt));\n}\n\nstring newFilename = AddSuffix(filename, String.Format("({0})", crcValue));	0
25503818	25503586	Is there any way to update a label in C# without using a timer?	private async void ChangeLabel()\n{\n   while(true)\n   {\n      await Task.Delay(100)\n      label1.Text = "lorem impus";\n   }\n}	0
7872313	7866532	How to create events for buttons created while runtime?	this.btnSaveSignal = new System.Windows.Forms.Button();\n    this.btnSaveSignal.Click += new System.EventHandler(this.btnSaveSignal_Click);\n    .\n    .\n    .\n    private void btnSaveSignal_Click(object sender, EventArgs e)\n    {\n        ...\n    }	0
11990693	11989901	How to convert RGB value to YCbCr using AForge	label4.Text = (ycrcb.Y *255).ToString();\n    label5.Text = ((ycrcb.Cr + 0.5)*255).ToString();\n    label6.Text = ((ycrcb.Cb + 0.5)*255).ToString();	0
8261529	8238955	Crystal Report Connection string from properties.settings winform c#	//Somewhere in my code:\n    foreach (CrystalDecisions.CrystalReports.Engine.Table tbCurrent in rdCurrent.Database.Tables)\n        SetTableLogin(tbCurrent);\n\n\n    //My set login method \n    private void SetTableLogin(CrystalDecisions.CrystalReports.Engine.Table table)\n    {\n        CrystalDecisions.Shared.TableLogOnInfo tliCurrent = table.LogOnInfo;\n\n        tliCurrent.ConnectionInfo.UserID = dbLogin.Username;\n        tliCurrent.ConnectionInfo.Password = dbLogin.Password;\n        if(dbLogin.Database != null)\n            tliCurrent.ConnectionInfo.DatabaseName = dbLogin.Database; //Database is not needed for Oracle & MS Access\n        if(dbLogin.Server != null)\n            tliCurrent.ConnectionInfo.ServerName = dbLogin.Server;\n        table.ApplyLogOnInfo(tliCurrent);\n    }	0
17554328	17553093	Rx, dynamically merging sources	var streams = new Subject<IObservable<int>>();\nvar mergedStreams = streams.Merge();\nvar mergedObserver = mergedStreams.Subscribe(...);\n\n// now create your streams\n...\n\n// add them to the streams subject\nstreams.OnNext(seq1);\nstreams.OnNext(seq2);\n...\n\nstreams.OnNext(seq3);\nstreams.OnNext(seq4);\n\n...\n// If we know there will be no more streams, tell the Subject...\nstreams.OnCompleted();	0
2590743	2590724	How do I format Int32 numbers?	x.ToString("00");\n String.Format("{0:00}",x);	0
12417960	12415521	How to drop and recreate a table in entity framework	dbContext.ExecuteStoreCommand("TRUNCATE TABLE myTable");	0
12673713	12673198	Get first row of join	var miniCompanies =\n(from companies in db.Companies \n join phones in db.Phones on companies.Id equals phones.CompanyId\n select new\n {\n     companies.Name,\n     phones.Phone,\n }).GroupBy(c=>c.Name).Select(c=>c.FirstOrDefault()).ToArray();	0
32490895	32490775	Set datagrid column width to star in codebehind	dataGrid.Columns[10].Width = new DataGridLength(double value here for initial size, DataGridLengthUnitType.Star);	0
34376392	34374714	How to trigger a timer using an external signal	class Program\n{\n    static Timer timer;\n\n    static void Main(string[] args)\n    {\n        //set timer interval of 3 seconds\n        timer = new Timer(interval: 3000);\n        timer.Elapsed += Timer_Elapsed;\n\n        InterruptPort sensor = new InterruptPort(/* sensor port information */);\n        sensor.OnInterrupt += new NativeEventHandler(sensor_OnInterrupt);\n    }\n\n    private static void sensor_OnInterrupt(uint data1,uint data2,DateTime time)\n    {\n        Console.WriteLine(DateTime.Now);\n        timer.Enabled = true;\n    }\n\n    private static void Timer_Elapsed(object sender, ElapsedEventArgs e)\n    {\n        Console.WriteLine(DateTime.Now); \n        timer.Enabled = false;\n        //do work\n    }\n}	0
10178779	10166970	How to use a C callback from C#?	[System::Runtime::InteropServices::UnmanagedFunctionPointerAttribute ( CallingConvention::Cdecl )]\npublic delegate long SRCCallback ( void *cb_data, float **data ) ;\n\nstatic  IntPtr CallbackNew ( SRCCallback ^ % func, RabbitConverter converter_type, int channels, int *error, void* cb_data ) { ... }	0
12532673	12532626	static readonly Dictionary<> declared anonymously	Dictionary<Guid, string> idsAndStrings = new Dictionary<Guid, string>\n{\n    { Guid.NewGuid(), "" },\n    { Guid.NewGuid(), "" },\n};	0
13277565	13277517	Replace all single quotes with two single quotes in a string	name = name.Replace("'", "''");	0
18503797	18489152	Updating order status in Prestashop via webservice api	RestRequest request;\nrequest = new RestRequest("api/orders/" + orderID, Method.GET);\nIRestResponse response = client.Execute(request);\n\nXElement orderXML = XElement.Parse(response.Content);\nXElement orderEl = orderXML.Descendants().FirstOrDefault();\norderEl.Element("current_state").Value = "10";    \n\nrequest = new RestRequest("api/orders", Method.PUT);\nrequest.AddParameter("xml", orderXML.ToString(), ParameterType.RequestBody);\nIRestResponse response2 = client.Execute(request);	0
1328821	1328746	How do I block all keyboard and mouse input to my WinForms app?	modalForm.ShowDialog(yourForm)	0
2533485	2533456	Linking a Text Box to a variable?	public string Text\n{\n  get\n  {\n    return richTextBox1.Text;\n  }\n}	0
4623413	4623395	Can i find request type in ActionExecutingContext object	filterContext.HttpContext.Request.IsAjaxRequest()	0
32634728	32634654	onbackpressed no suitable method found to override xamarin	protected override void OnBackPressed()	0
22778407	22778314	How to set a parameter in json when json is string format	double Latitude = 47.64325;\ndouble Longitude = -122.14196;\nstring json = "{" + "\"" + "device_id" + "\"" + ":" + "\"" + "nishant" + "\"" + "," + "\"" + "position" + "\"" + ":" + " \"" + Latitude\n                + "," + Longitude + "\"" + " }";	0
33431190	33431086	Parsing strings into two parts (like an email address) C#	MailAddress addr = new MailAddress("Name@yahoo.com");\nstring name= addr.User;\nstring domain = addr.Host;	0
561268	561020	string.Format() parameters	int i = 0;\nlong sum = 0;\nwhile (sum < int.MaxValue)\n{\n    var s = sizeof(char) * ("{" + i + "}").Length;\n    sum += s; // pseudo append\n    ++i;\n}\nConsole.WriteLine(i);\nConsole.ReadLine();	0
7230622	7230551	Login to website from app	public static void GetFileWithCredentials(string userName, string password, string url)\n{\n\n    using (WebClient wc = new WebClient())\n    {\n        wc.Credentials = new NetworkCredential(userName, password);\n        string xml = wc.DownloadString(url);\n\n        XmlDocument tournamentsXML = new XmlDocument();\n        tournamentsXML.LoadXml(xml);\n    }\n\n}	0
20076105	20076076	Passing values from variables in Insert query in C#, ASP.NEt for MSSQL Server Database	"(Select [SubCategory].ID from SubCategory where Kategorie = @SubCategory)," +\n"(SELECT [BusinessSector5].ID FROM BusinessSector5 where Description_DE = @BusinessSector5));",con))	0
19058793	19057861	How clear GetValidationErrors to perform a SaveChange()	context.Configuration.ValidateOnSaveEnabled = false;	0
4625143	4624994	Bind a ListView ItemSource to two different GetSet properties in the View (MVVM)	Source="{Binding Path=DataContext.ImageTypes, \n         RelativeSource={RelativeSource FindAncestor, \n         AncestorType={x:Type UserControl}}}"	0
7802892	7802822	All Possible Combinations of a list of Values	static void Main(string[] args)\n{\n\n    GetCombination(new List<int> { 1, 2, 3 });\n}\n\nstatic void GetCombination(List<int> list)\n{\n    double count = Math.Pow(2, list.Count);\n    for (int i = 1; i <= count - 1; i++)\n    {\n        string str = Convert.ToString(i, 2).PadLeft(list.Count, '0');\n        for (int j = 0; j < str.Length; j++)\n        {\n            if (str[j] == '1')\n            {\n                Console.Write(list[j]);\n            }\n        }\n        Console.WriteLine();\n    }\n}	0
2360387	2360252	How to fix flicker in a WinForms form?	this.DoubleBuffered = true;	0
26900632	26887822	Error when removing button programmatically with custom template	button.MouseEnter += (s, e) => { /*begin Storyboard*/};\nbutton.MouseLeave += (s, e) => \n    {\n        if (EquipmentFilters.Contains(button))\n        {\n            //begin storyboard\n        }                           \n    };\nbutton.Click += (o, i) =>\n    {\n        EquipmentFilters.Remove(button);\n    };	0
7844496	7844410	Escaping ONLY contents of Node in XML	string s = "<item><name> Foo > Bar </name></item>";\n    s = Regex.Replace(s, @"<[^>]+?>", m => HttpUtility.HtmlEncode(m.Value)).Replace("<","ojlovecd").Replace(">","cdloveoj");\n    s = HttpUtility.HtmlDecode(s).Replace("ojlovecd", "&gt;").Replace("cdloveoj", "&lt;");\n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(s);	0
8220798	8213566	Fading UILabel out, change text, fade back in: only fading in is animated	btn.TouchUpInside += delegate {\n    UIView.Animate (0.5f, delegate {\n        lbl.Alpha = 0.0f;\n    }, delegate {\n        UIView.Animate (0.5f, delegate {\n            lbl.Alpha = 1.0f;\n        });\n    });\n};	0
18891497	18891207	How to get value from a specific child element in XML using XmlReader?	if(reader.ReadToDescendant("response"))\n            {\n                reader.Read();//this moves reader to next node which is text \n                result = reader.Value; //this might give value than \n                break;\n            }	0
14297911	14297902	How to set Button label in Windows Phone	Button.Content = "Your Label";\n\n<Button Content="Your Label"/>	0
32939660	32939598	How to add incremental numbers to the end of a filename when saving in asp.net web forms c# application?	int i = 0;\n    string filename = fu_new_doc_vsn.FileName;\n    if (fu_new_doc_vsn.HasFile)\n    {\n        while (System.IO.File.Exists(Server.MapPath("~/Data/") + filename))\n        {\n            i++;\n            filename = fu_new_doc_vsn.Name + " (" + i.ToString() + ")" + Path.GetFileNameWithoutExtension(fu_new_doc_vsn.FileName);\n        }\n        fu_new_doc_vsn.PostedFile.SaveAs(Server.MapPath("~/Data/") + filename);\n    }	0
6756322	6756075	set some consecutive bits in a byte	public static byte SetBits(byte oldValue, byte newValue, int startBit, int bitCount)\n{\n    if (startBit < 0 || startBit > 7 || bitCount < 0 || bitCount > 7 \n                     || startBit + bitCount > 8)\n        throw new OverflowException();\n\n    int mask = (255 >> 8 - bitCount) << startBit;\n    return Convert.ToByte((oldValue & (~mask)) | ((newValue << startBit) & mask));\n}	0
7506591	7506573	How to extract string between 2 markers using Regex in .NET?	HtmlWeb web = new HtmlWeb();\nHtmlDocument doc = web.Load("http://stackoverflow.com");\nstring html = doc.DocumentNode.Descendants("body").Single().InnerHtml;	0
8418954	8118587	Getting the public certificate from a mail which is signed and encrypted	var rawEmailBytes = pseudo_GetRawEmail();  // function that gets the raw email\nvar signedCmsBytes = psuedo_GetSignedCmsData(rawEmailBytes)   // would pull out the signed package bytes from the email\nvar signedCms = new SignedCms();\nsignedCms.Decode(signedCmsBytes)\n\nforeach (var certificate in signedCms.Certificates) {\n   psuedo_StoreCertificate(certificate)   // store certificate using the cert manager.\n}	0
1470322	1470291	Getting data from remote service if not cached in database - suggestion needed	public class CachingRepository : ICustomerRepository\n{\n    private readonly ICustomerRepository remoteRep;\n    private readonly ICustomerRepository localRep;\n\n    public CachingRepository(ICustomerRepository remoteRep, ICustomerRepository localRep)\n    {\n        this.remoteRep = remoteRep;\n        this.localRep = localRep;\n    }\n\n    // implement ICustomerRepository...\n}	0
24785289	24784347	JSON.NET Deserialize Nested data from URL	Result me = new Result()\n        {\n           address1 = (string)jResult["results"][0]["address1"], \n           city = (string)jResult["results"][0]["city"] ,\n           state  = (string)jResult["results"][0]["state"] ,\n           zip = (string)jResult["results"][0]["zip"]\n        };	0
33731917	33728447	C# Find All Missing Segments In Time	private static List<Tuple<TimeSpan,TimeSpan>> ComputeMissingTimeSpans(List<Tuple<TimeSpan,TimeSpan>> availableIntervals, TimeSpan minSpan, TimeSpan maxSpan)\n    {\n        List<Tuple<TimeSpan,TimeSpan>> missingTime = new List<Tuple<TimeSpan,TimeSpan>>();\n        if(availableIntervals.Count == 0)\n        {\n            missingTime.Add(new Tuple<TimeSpan, TimeSpan>(minSpan, maxSpan));\n            return missingTime;\n        }\n\n        foreach(var interval in availableIntervals){\n            if((interval.Item1 - minSpan).TotalSeconds > 1 ) \n            {\n                missingTime.Add(new Tuple<TimeSpan, TimeSpan>(minSpan, interval.Item1.Add(TimeSpan.FromSeconds(-1))));\n            }\n\n            minSpan = interval.Item2.Add(TimeSpan.FromSeconds(1));\n        }\n\n        if((maxSpan - minSpan).TotalSeconds > 1)\n            missingTime.Add(new Tuple<TimeSpan, TimeSpan>(minSpan, maxSpan));\n\n        return missingTime;\n    }	0
9165130	9165079	AutoResetEvent Set called after timeout	public void Method1()\n{\n  // Reset the wait handle I'll be using...\n  MyWaitHandle.Reset();\n\n  //do something\n  //wait for the signal or timeout\n  MyWaitHandle.WaitOne(10000);\n  //do something else on receiving signal or after timeout\n}	0
29645528	29645097	Enabling/disabling menu items - Expression Blend	private void MenuItem_Click(object sender, RoutedEventArgs e)\n{\n   ((MenuItem)sender).IsEnabled = false;\n}	0
18539951	18539863	Is it possible to add another Window with XAML?	private void Button_Click(object sender, RoutedEventArgs e)\n{\n    Window1 w1 = new Window1();\n    w1.Show();\n}	0
2397968	2397860	C# WinForms - Smart TextBox Control to auto-Format Path length based on Textbox width 	using System;\nusing System.ComponentModel;\nusing System.Windows.Forms;\n\nclass PathLabel : Label {\n  [Browsable(false)]\n  public override bool AutoSize {\n    get { return base.AutoSize; }\n    set { base.AutoSize = false; }\n  }\n  protected override void OnPaint(PaintEventArgs e) {\n    TextFormatFlags flags = TextFormatFlags.Left | TextFormatFlags.PathEllipsis;\n    TextRenderer.DrawText(e.Graphics, this.Text, this.Font, this.ClientRectangle, this.ForeColor, flags);\n  }\n}	0
29875326	29875238	get indexes of different elements from arrays with equal length using Linq	int[] diff = Enumerable.Range(0, arr1.Length).Where(i => arr1[i] != arr2[i]).ToArray();	0
19458372	19458299	Right-Aligning printed text	rightMargin - measuredStringWidth	0
6219879	6219801	Refactoring a Dictionary, changing key type	public class Key { public Key(object adaptee) { ... } }	0
12780265	12779494	How to copy .EXE file contents to clipboard?	// copying to the clipboard\nvar fileContent = File.ReadAllBytes("Path\\to\\exefile.exe");\nClipboard.SetData(DataFormats.Text, Convert.ToBase64String(fileContent));\n\n// reading from the clipboard\nvar readBackFileContent = (string)Clipboard.GetData(DataFormats.Text);\nFile.WriteAllBytes("destination.exe", Convert.FromBase64String(readBackFileContent));	0
27695675	27695489	Send Email After Button Click in ASP.net C#	foreach(string email in emailArray)\n{\n     SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587);\n     smtp.UseDefaultCredentials = false;\n     smtp.Credentials = new NetworkCredential("tayyib@gmail.com", "xxxxxxxxx");\n     smtp.EnableSsl = true;\n\n     MailMessage msg = new MailMessage("tayyib@gmail.com", email); \n     msg.Subject = "Test1";\n     msg.Body = "Test2";\n\n     smtp.Send(msg);\n }	0
5718351	5718285	C# create child events from a parent event	var current = startDate;\ndo {\n  list.Add(new MyEvent("My Event", current));\n  current = current.AddDays(7);\n} while (current < endDate);	0
14084622	14084607	VB.NET Interface Property with Getter but no Setter	Readonly Property PropNeeded() As Integer	0
33151288	33150846	WPF: Rotate a rectangle with slider	private void sldRotate_ValueChanged(object sender, RoutedPropertyChangedEventArgs<double> e)\n{\n    if (_shape != null)\n    {\n        var rt = new RotateTransform();\n        rt.Angle = sldRotate.Value;\n        _shape.RenderTransform = rt;\n        _shape.RenderTransformOrigin = new Point(0.5, 0.5);\n    }\n}	0
9075325	9075236	How to sort and order merged DataSets	// Assuming the merged table is the first and only table in the DataSet.\nDataView dv = new DataView(dataSet1.Tables[0]);\n\ndv.Sort = "date, reason DESC";	0
26072153	26071788	TextBox Content as a name for Textfile	string filename = textBox1.Text;\nstring path = System.IO.Path.Combine(@"E:\Majel\Tic Tac Toe\TextFiles\", filename + ".txt");\nSystem.IO.FileInfo file = new System.IO.FileInfo(path);\nfile.Create();	0
5819422	5819357	How to get the size of arrays packed as value in a Dictionary<K,V> in C#?	var lrowCount = ltableData.Values.First().Length;\n// or\nvar lrowCount = ltableData.First().Value.Length;	0
3744808	3260390	DBMetal (SQLite): "Sequence contains more than one element" with multiple foreign keys	INTEGER PRIMARY KEY	0
12737287	12717516	Disabled button in WPF	public IInputElement DrawingTarget { get { return _canvas; } }	0
19822268	19821548	Sum up column values in DataTable based on the value of another column	var dt = new DataTable();\ndt.Columns.Add("Amount", typeof(int));\ndt.Columns.Add("Count", typeof(int));\ndt.Rows.Add(20, 2);\ndt.Rows.Add(42, 1);\ndt.Rows.Add(78, 5);\ndt.Rows.Add(91, 2);\nvar result = from DataRow x in dt.Rows\n                group x by ((int)x["Amount"]) / 50 into grp \n                select new {LowerBoundIncl = grp.Key * 50, \n                        UpperBoundExcl = (grp.Key + 1) * 50, \n                        TotalCount = grp.Sum(y => (int) y["Count"])};	0
5787658	5787595	How can I get all the controls in a namespace?	class Program\n{\n    static void Main()\n    {\n        var controlType = typeof(Control);\n        var controls = controlType\n            .Assembly\n            .GetTypes()\n            .Where(t => controlType.IsAssignableFrom(t) && \n                        t.Namespace == "System.Windows.Forms"\n            );\n        foreach (var control in controls)\n        {\n            Console.WriteLine(control);\n        }\n    }\n}	0
4883526	4883481	Finding first day of calendar	var firstDayOfMonth = new DateTime(year, month, 1);\nDateTime startOfCalendar = \n    FirstDayOfWeekOnOrBefore(\n        firstDayOfMonth,\n        DayOfWeek.Monday\n    );\n\npublic static DateTime FirstDayOfWeekOnOrBefore(\n    DateTime date,\n    DayOfWeek dayOfWeek\n) {\n    while(date.DayOfWeek != dayOfWeek) {\n        date = date.AddDays(-1);\n    }\n    return date;\n}	0
568378	542850	How can I insert an image into a RichTextBox?	{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860 hex data}\n{\pict\pngblip\picw10449\pich3280\picwgoal5924\pichgoal1860\bin binary data}	0
24117908	24117581	Truncate DataGridView fields so it doesnt exceed 10 characters?	dgvEvents.Rows[n].Cells[1].Value = dr[1].TrimEnd(' ').ToString();	0
16852418	16852360	add a scheduled task using CMD prompt	startInfo.Arguments = "/C schtasks /create /tn Inc-Andro-BU /tr" +         \n                       inbackpath + "/sc minute /mo 10 /ru SYSTEM";	0
4180490	4180475	Is there a C# equivalent of Java's LineNumberReader?	class LineNumberTextReader : TextReader\n{\n    private readonly TextReader reader;\n    private int b;\n    private int line;\n\n    public LineNumberTextReader(TextReader reader)\n    {\n        if (reader == null) throw new ArgumentNullException("reader");\n        this.reader = reader;\n    }\n\n    public int Line\n    {\n        get { return this.line; }\n    }\n\n    public override int Peek()\n    {\n        return this.reader.Peek();\n    }\n\n    public override int Read()\n    {\n        int b = this.reader.Read();\n        if ((this.b == '\n') || (this.b == '\r' && b != '\n')) this.line++;\n        return this.b = b;\n    }\n\n    protected override void Dispose(bool disposing)\n    {\n        if (disposing) this.reader.Dispose();\n    }\n}	0
4507829	4507766	Using Generics with LINQ Inheritance	public static IQueryable<T> GetSCOs<T>(SCODataContext dc) where T : SCO\n{\n    return dc.SCOs.OfType<T>();\n}	0
3714354	3714333	XmlSerializer requires XmlInclude for public method with generic constraint if type in another assembly AND requires that type to be serialiable!	namespace BarStuff {\n  //the serializer is perfectly happy with me\n  public class DummyBar{}\n\n  //the serializer doesn't like me\n  public class Bar{\n  ...\n  }\n\n  ...\n}\n\nusing BarStuff;\nnamespace FooStuff {\n  [XmlInclude(typeof(DummyBar))]\n  public class Foo {\n    public T GetBar<TBar, T>( string key ) where TBar : Bar<T> {\n      ...\n    }\n  }	0
8594985	8594955	How do you count every subfolder under the Outlook mailbox?	public int countRootFolders(Microsoft.Office.Interop.Outlook.MAPIFolder aFolder)\n{\n    int rootCount = aFolder.Folders.Count;\n\n    foreach (Microsoft.Office.Interop.Outlook.MAPIFolder subfolder in aFolder.Folders)\n    {\n        rootCount += countRootFolders( subFolder );\n    }\n\n    return rootCount;\n}	0
21309294	21177341	How do I reduce high CPU usage because of a C# Windows forms custom control being redrawn frequently?	void Application_Idle(object sender, EventArgs e)\n {\n      Invalidate();\n      LevelView.Update();\n }	0
13447276	13447248	C# how to assign List<T> without being a reference?	name_list2 = new List<string>(name_list1);	0
823451	823430	How to order a IEnumerable<T> of anonymous type?	var sortedList = ordersList.OrderBy(p => p.ProductName).ToList();	0
4249887	4249632	String to Enum with Description	public static T GetEnumValueFromDescription<T>(string description)\n{\n    MemberInfo[] fis = typeof(T).GetFields();\n\n    foreach (var fi in fis)\n    {\n        DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);\n\n        if (attributes != null && attributes.Length > 0 && attributes[0].Description == description)\n            return (T)Enum.Parse(typeof(T), fi.Name);\n    }\n\n    throw new Exception("Not found");\n}	0
3351111	2945726	Setting a min/max zoom for Bing maps in Silverlight	public class MyMapMode : Microsoft.Maps.MapControl.Core.MercatorMode\n{\n    public Range<double> MapZoomRange = new Range<double>(1.0, 10.0);\n    protected override Range<double> GetZoomRange(Location center)\n    {\n        return this.MapZoomRange;\n    }\n}	0
32612374	32611881	I'm trying to select an element I'm working with:	IWebElement element = webDriver.FindElement(By.XPath("//a[contains(text(), 'Enter')]"));	0
24853332	24853309	How to get mismatch position using Linq or lambda operation on two string array	var mismatches = Enumerable.Range(0, Math.Min(list1.Length, list2.Length))\n                           .Where(i => list1[i] != list2[i])\n                           .ToList();	0
8884248	8880791	How to trigger an event when any of CheckState values in CheckListBox is changed	private void clbAllRooms_ItemCheck(object sender, ItemCheckEventArgs e) {\n        this.BeginInvoke(new MethodInvoker(() => Update_rtbPrice()));\n    }	0
27867897	27867594	DateTime.Now Date Format and Windows Settings	Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US");	0
20467120	20424673	How to retrieve less variable using dotless asp.net	string GetLessVariableByName(string name, string lessContent) {\n    int optimisation = 1;\n    Func<IStylizer> defaultStylizer = () => new PlainStylizer();\n    Func<IImporter> defaultImporter = () => new Importer();\n    Func<Parser> defaultParser = () => new Parser(optimisation, defaultStylizer(), defaultImporter());\n    Func<Env> defaultEnv = () => { return new Env(); };\n    Env env = defaultEnv();\n    Parser parser = defaultParser();\n    var tree = parser.Parse(lessContent.Trim(), "tmp.less");\n    var rule = tree.Rules.ToArray()[0];\n    Node node = rule.Evaluate(env);\n    var variableValue = tree.Variable(name, node);\n\n    return variableValue == null ? null : variableValue.Value.ToString();\n}	0
18345135	18344489	How to use an object as a data source c#	public class ItemDataSource : BindingSource\n{\n    private ICollection<ItemData> list;\n    public ItemDataSource()\n    {\n        try\n        {\n            list = QBCom.GetItemList();\n        }\n        catch (Exception e)\n        {\n            list = new List<ItemData>();\n        }\n        this.DataSource = list;\n    }\n    public ItemDataSource(IEnumerable<ItemData> data)\n    {\n        list = data.ToList();\n        this.DataSource = list;\n    }\n}	0
10640530	10638421	Stored procedure list and parameter number used in conjunction with ComboBox	SELECT\n    sprocs.ROUTINE_NAME,\n    parms.PARAMETER_NAME,\n    parms.DATA_TYPE\nFROM\n    INFORMATION_SCHEMA.ROUTINES sprocs\n    LEFT OUTER JOIN INFORMATION_SCHEMA.PARAMETERS parms ON parms.SPECIFIC_NAME = sprocs.ROUTINE_NAME\nWHERE\n    sprocs.ROUTINE_TYPE = 'PROCEDURE'\n    --AND PATINDEX('/*<SomeKeyToSearch>*/', sprocs.ROUTINE_DEFINITION) > 0	0
4462283	4462133	C# User Control - How to tell containing object the control needs data	// Your sample control\npublic class MyUserControl : Control\n{\n    public event EventHandler<EventArgs> INeedData;\n    public Data Data {get; set;}\n\n    private class DoSomething()\n    {\n        if(INeedData!=null) INeedData(this,null);\n    }\n}\n\n...\n\n// Your Form, in the case that the control isn't already added.\nvar _myUserControl = new MyUserControl();\nprivate void Form1_Load(object sender, EventArgs e)\n{\n    _myUserControl.INeedData += new EventHandler<EventArgs>(MyUserControl_INeedData);\n    this.Controls.Add(myUserControl);\n}\n\nvoid MyUserControl_INeedData(object sender, EventArgs e)\n{\n    _myUserControl.Data = SomeData;\n}	0
6585314	6585017	Textbox text from background worker?	private void bgw1_DoWork(object sender, DoWorkEventArgs e)\n{\n  // looping through stuff\n  {\n    this.Invoke(new MethodInvoker(delegate { Text = textBox1.Text; }));\n  }\n}	0
25806810	25806521	Add shape to top right corner of power point slide using C# and Power point addin	PowerPoint.Application ppApp = Globals.ThisAddIn.Application;\nleft = ppApp.ActivePresentation.PageSetup.SlideWidth - //my image size - //my margin;	0
2877886	2877598	Insert a Join Statement - (Insert Data to Multiple Tables) - C#/SQL/T-SQL/.NET	create table A (\n    id_a int not null identity(1,1) primary key,\n    name varchar(100))\ncreate table B (\n    id_b int not null identity(1,1) primary key,\n    id_a int null,\n    name_hash varbinary(16));\n\ninsert into A (name)\noutput inserted.id_a, hashbytes('MD5', inserted.name)\ninto B (id_a, name_hash)\nvalues ('Jonathan Doe')\n\nselect * from A\nselect * from B	0
11832485	11829559	How can I detect if a file has Unix line feeds (\n) or Windows line feeds (\r\n)?	public bool TryDetectNewLine(string path, out string newLine)\n    {\n        using (var fileStream = File.OpenRead(path))\n        {\n            char prevChar = '\0';\n\n            // Read the first 4000 characters to try and find a newline\n            for (int i = 0; i < 4000; i++)\n            {\n                int b;\n                if ((b = fileStream.ReadByte()) == -1) break;\n\n                char curChar = (char)b;\n\n                if (curChar == '\n')\n                {\n                    newLine = prevChar == '\r' ? "\r\n" : "\n";\n                    return true;\n                }\n\n                prevChar = curChar;\n            }\n\n            // Returning false means could not determine linefeed convention\n            newLine = Environment.NewLine;\n            return false;\n        }\n    }	0
29352846	26149510	bypass service ID from App pool to determine actual username of user ASP.NET C#	string UserName = System.Threading.Thread.CurrentPrincipal.Identity.Name;	0
31572854	31572677	Counting the number of times a team name has occurred in a list and putting the answer in a listbox	var dict = arr\n        .GroupBy(x => x)\n        .Where(x => selectedTeams.Contains(x))\n        .ToDictionary(x => x.Key, x => x.Count());	0
1905368	1905025	how to add function inside select query	// doesn't have to be static - just simpler for my test\nstatic string getValidDescription(string description)\n{\n    // handle nulls safely (could return a default here)\n    if (description == null) return null;\n    // for example only...\n    return CultureInfo.CurrentCulture.TextInfo\n        .ToTitleCase(description);\n}\n\nvar qry =\n    from details in doc.Root.Elements("detail")\n    select new FeedResource\n    {\n        Title = (string)details.Element("title"),\n        Host = (string)details.Element("link"),\n        Description = getValidDescription((string) details.Element("description")),\n        PublishedOn = (DateTime?)details.Element("pubDate"),\n        Generator = (string)details.Element("generator"),\n        Language = (string)details.Element("language")\n    };	0
23417722	23415983	Entity Framework, Get element from related table based on includes	public List<string> GetClientAndPermittedActivities(int clientId)\n{\n    return ReadAllRaw()\n            .Where(c => c.Id == clientId)\n            .SelectMany(\n                           ct => ct.ClientType\n                                   .Role\n                                   .PermittedActivities,\n                           (s, c) => c.Uid\n                       )\n            .ToList();\n}	0
16078018	16077741	Split a complex string into a list of classes using regular expressions and lambda in C#	string input = "a:b,c";\n\nint colon = input.IndexOf(':');\nstring left = input.Substring(0, colon);\nstring right = input.Substring(colon + 1);\n\nList<MyClass> result = right.Split(',')\n                            .Select(x => new MyClass\n                            {\n                                Column1 = left,\n                                Column2 = x,\n                            })\n                            .ToList();	0
7747401	7747370	How to replace apostrophe with double apostrophe in string?	string s = "good overview of ESP's in more detail than you probably need.";\nstring escaped = s.Replace("'","''");	0
30103766	30103604	How do I return a generic list with QueryOver	// Users u - will serve as an alias source below\nUsers u = null;\nIList<Users> users = this.Session.QueryOver<Users>()\n        .Where(f => f.role == role)\n        .SelectList(list => list        // here we set the alias \n                .Select(p => p.username) .WithAlias(() => u.username)\n                .Select(p => p.email)    .WithAlias(() => u.email)\n                .Select(p => p.firstname).WithAlias(() => u.firstname)\n        )\n        // here we Transform result with the aliases into Users\n        .TransformUsing(Transformers.AliasToBean<Users>())\n        .List<Users>();	0
2927872	2926958	How to insert null value for numeric field of a datatable in c#?	if(dr["Mob2"] == "")\n  dr["Mob2"] =null;	0
23702599	23701669	Reading the value of cookies in cookie-aware WebClient	public static IEnumerable<Cookie> GetAllCookies(CookieContainer cookieContainer)\n{\n    var domainTable = (Hashtable)cookieContainer\n                            .GetType()\n                            .InvokeMember(\n                                name: "m_domainTable",\n                                invokeAttr: BindingFlags.NonPublic | BindingFlags.GetField | BindingFlags.Instance,\n                                binder: null,\n                                target: cookieContainer,\n                                args: new object[] { });\n\n    return domainTable.Keys.Cast<string>()\n                .Select(d => cookieContainer.GetCookies(new Uri("http://" + d.TrimStart('.'))))\n                .SelectMany(c => c.Cast<Cookie>());\n\n}	0
20227222	20226734	RegEx - Find and Replace while ignoring a number in the middle?	var r = new Regex(@"(\d+)(\. )");\nvar input = "This is a test No. 42. Hello Nice People";\nvar output = r.Replace(input, "$1, ");	0
17008433	17003469	How to ensure right set of data in objects returned from LINQ to DataSet Quer	Var CDNumbers =\n    From CDNumber in CollectionsDataSet.CD.AsEnumerable()\n    Where CDNumber.Field<int?>("CDNumber") != null\n    Select CDNumber.Field<int?>("CDNumber");	0
9123049	9121088	Tasks in database with multiple programs processing them - how to ensure each one is processed exactly once?	InstanceContextMode.Single	0
8912369	8912353	Can I 'invert' a bool?	ruleScreenActive = !ruleScreenActive;	0
33103676	33103524	How can I pass an event from one class to a child object?	public event  EventHandler TextChanged\n{\n    add\n    {\n        textbox.TextChanged += value;\n    }\n    remove\n    {\n        textbox.TextChanged -= value;\n    }\n}	0
24750171	24735948	How to resolve 'PInvoke function has unbalanced the stack Error' in Windows Form Application?	//Windows API for resizing the window.\n[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]\npublic static extern int SendMessage(IntPtr hWnd, uint Msg, long lParam, long wParam);\n\n[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]\npublic static extern bool ReleaseCapture();\n\n[DllImport("user32.dll", CallingConvention = CallingConvention.StdCall)]\npublic static extern bool ShowWindow(IntPtr hWnd, int cmdShow);	0
14491862	14481008	Twitter sdk wp8	TwitterService service = new TwitterService("<my app key>", "<my app secret>");\nservice.GetTweet(294183806548733952, \n    (tweet, response) => Dispatcher.BeginInvoke(() => \n            MessageBox.Show(tweet.Text, tweet.Author.ScreenName, MessageBoxButton.OK)));	0
11450044	11448955	Generate a PDF poster in C#	private PdfContentByte _pcb; \nDocument document = new Document();\n\nFileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);\nPdfReader Mypdfreader= new PdfReader(fileStream);\n PdfTemplate background = writer.GetImportedPage(Mypdfreader, 1);\n document.NewPage();\n_pcb = writer.DirectContentUnder;\n_pcb.AddTemplate(background, 0, 0);\n _pcb = writer.DirectContent;\n_pcb.BeginText();\n         _pcb.SetFontAndSize(BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false), 10);\n _pcb.ShowTextAligned(PdfContentByte.ALIGN_LEFT, text, 10, 5, 0);//10,5 are x and y coordinates resp.\n _pcb.EndText();\n\n writer.Flush();\nfileStream.Close();	0
25736038	15082285	Sending a string containing special characters through a TcpClient (byte[])	//data to send via tcp or any stream/file\nbyte[] message_to_send = UTF8Encoding.UTF8.GetBytes("am??");\n\n//when receiving, pass the array in this to get the string back\nstring message received = UTF8Encoding.UTF8.GetString(message_to_send);	0
18077114	18076888	How to play/set songs/radio station in itunes using API	obj.OpenURL("http://108.166.161.205:8795");	0
19011575	18994339	How to get the value of root element in xml	var xelement = XElement.Parse(outputtext);\n            rate = (double)xelement;	0
15638228	15638176	Get date string from count of days since Epoch C#	var epoch = new DateTime(...);  // Your epoch (01/01/0001 or whatever)\nvar yourDate = epoch.AddDays(days_since_epoch);	0
11016751	11015718	Strong Type Data Set : Override column get : set	namespace ExtensionMethods\n{\n    public static class MyExtensions\n    {\n        public static void SetEncryptColumn(this DataSetType.DataTableRow row, string value)\n        {\n            row.Encrypt = EncryptValue(value);\n        }\n\n        public static string GetEncryptColumn(this DataSetType.DataTableRow row)\n        {\n            return DecryptValue(row.Encrypt);\n        }\n    }   \n}	0
12320226	12320177	how to get items from a dictionary of lists with linq	public IEnumerable<Ability> GetAbilitiesForClasses(string[] asClassNames, int iLevel)\n{\n    return Classes\n           .Where(X => asClassNames.Contains(X.Name))\n           .SelectMany(X => X.Abilities)\n           .Where(X => X.Level <= iLevel)\n           .ToList();\n}	0
22415587	22415463	How to create a file with FileOptions.Encrypted in C#?	Encrypted is specified for options and file encryption is not supported on the current platform.	0
25776358	25776288	Detect Key Press while looping infinitely	new Thread(delegate() { \n\nwhile(true)\n{\n //...\n}\n\n}).Start();	0
28768734	28768686	Get items which contain any of the strings in a Collection	var dividend = yearItem.GetType().GetProperties().\nWhere(x => x.Name.Contains("Record") || x.Name.Contains("Payable") || x.Name.Contains("Cash"));	0
22834971	22834600	Temporary add node to XDocument	doc.Root.ReplaceWith(new XElement("MyTempRoot", doc.Root));	0
21490447	21490413	How to generate a uniformly random number U(-1,1) in C#?	var rand = new Random();\nvar value = rand.NextDouble() * 2 - 1;	0
28525358	28525243	Which folder to be used for user downloads in Windows Phone 8.1	KnownFolders.SavedPictures	0
21584733	21584658	How to set the title on Chart through Code in C#	// Set title.\nthis.chart1.Titles.Add("Sales");	0
6696647	6696603	C# - Xml Element with attribute and node value	[XmlText]\npublic string Text;	0
1644466	1644438	When the user clicks a button, I want all other buttons to be disabled	DisableControls(Control c)\n{\n    c.Enable  = false;\n    foreach(Control child in c.Controls)\n       DisableControls(child)\n}	0
17647174	17647141	How Factorial logic works?	factorial(0) := 1\nfactorial(1) := 1\nfactorial(n) := n * factorial(n - 1)	0
27413810	27412131	c# send int array via serial port to arduino	char recdata[10];\nint bytes = 0;\nif(Serial.available())\n{     \n  bytes = Serial.readBytes(recdata, MAX_LENGTH);\n  checkdata(); //function which checks the received data\n}	0
9208908	9197259	Listbox Selected Value Issue	int intClient = 0;\n        try\n        {\n            intClient = (int)lbxClient.SelectedValue;\n        }\n        catch (Exception)\n        {\n            intClient = 0;\n        }	0
19527344	19476856	How to configure StructureMap for asp.net MVC 5	private readonly string _path =\n            ConfigurationManager.AppSettings["vp"].ToString(CultureInfo.InvariantCulture);	0
304474	304435	Mocking a COM object	public class Table\n{\n   public Table(IMapInfo map)\n   {\n      _map = map;\n   }\n\n   public string Name\n   {\n      get \n      {\n        string value = _map.Eval("myexpression");\n        if (String.IsNullOrEmpty(value))\n        {\n            value = "none";\n        }\n        return value;\n      }\n   }\n\n   private IMapInfo _map;\n}\n\n[TestFixture]\npublic class TableFixture // is this a pun?\n{\n   [Test]\n   public void CanHandleNullsFromCOM()\n   {\n       MockRepository mocks = new MockRepository(); // rhino mocks, btw\n       IMapInfo map = mocks.CreateMock<IMapInfo>();\n\n       using (mocks.Record())\n       {\n          Expect.Call(map.Eval("myexpression").Return(null);\n       }\n\n       using (mocks.PlayBack())\n       {\n          Table table = new Table(map);\n          Assert.AreEqual("none", table.Name, "We didn't handle nulls correctly.");\n       }\n\n       mocks.verify();\n   }\n}	0
31533373	31532953	MySQL Load Data Infile	public int Import(string path)\n{\n   try\n   {\n      string cmd = "LOAD DATA INFILE '" + path + "' INTO TABLE zen_hardware.products FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n'";\n      int a = MySqlHelper.ExecuteNonQuery(conn.Connect(),cmd);\n      return a;\n   }\n   catch\n   {\n      return -1;\n   }\n}	0
27879909	27879724	How to realize accurate time counter (millisecond precision)	var watch = Stopwatch.StartNew();\n\n//Do work\n\nConsole.WriteLine("Time elapsed: {0}", watch.ElapsedMilliseconds);	0
10995427	10995363	WPF connection to a SQL Server Compact database	Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();\ndlg.DefaultExt = ".sdf";\ndlg.Filter = "Database file (.sdf)|*.sdf";\n\nNullable<bool> result = dlg.ShowDialog();\n\nif (result == true)\n{\n    string Myfile = dlg.FileName;\n}	0
21448047	21432591	WP8 get Grid (content panel) height in run time	public MainPage()\n        {\n            InitializeComponent();\n\n            this.Loaded += new RoutedEventHandler(DisplayMessage);\n        }\n\nvoid DisplayMessage(object sender, RoutedEventArgs e)\n        {\n            MessageBox.Show(ContentPanel.ActualHeight.ToString());\n        }	0
29497756	28420265	Using WCF Service to Access Data in a Windows Service That's Hosting the WCF Service	protected override void OnStart(string[] args)\n{\n    if (_serviceHost != null)\n    {\n        _serviceHost.Close();\n    }\n\n    _counterObject = new CounterClass();\n    _counterObject.StartCounting();\n\n    _wcfService = new CounterWCFService(_counterObject);\n\n    _serviceHost = new ServiceHost(_wcfService);\n    _serviceHost.Open();\n}	0
12682038	12681685	Dynamic linq expression for EF	public static Expression<Func<MyEntity, int?>> EqualsValue(MyType myType, int value) {\n  return (e) => GetItem(myType)(e) == value;\n}	0
29687933	29687739	C# - How to tell if DataColumn supports nulls?	var Results = DataAdapter.FillSchema(NewData, SchemaType.Source, tableName);	0
25228478	25228447	C# How do I convert this string[] (from textbox) to a list or an array of IPAddresses	List<IPAddress> addresses = new List<IPAddress>();\nforeach (string input in this.textBox1.Lines)\n{\n    IPAddress ip;\n    if (IPAddress.TryParse(input, out ip))\n    {\n        addresses.Add(ip);\n    }\n    else\n    {\n        Console.WriteLine("Input malformed: {0}", input);\n    }\n}	0
1328489	1328369	Is it possible to send an Object's Method to a Function?	private class MyObject\n{\n    public bool Method1() { return true; } // Your own logic here\n    public bool Method2() { return false; } // Your own logic here\n}\n\nprivate static bool MyFunction(Func<bool> methodOnObject)\n{\n    bool returnValue = methodOnObject();\n    return returnValue;\n}    \n\nprivate static void OverallFunction()\n{\n    MyObject myObject = new MyObject();\n\n    bool method1Success = MyFunction(myObject.Method1);\n    bool method2Success = MyFunction(myObject.Method2);\n}	0
23339275	23269222	Assembly Name and Default Namespace	1. Change the assembly name and/or namespace name in project -> properties\n2. Localization DLL uses(assumes) assembly name as the default namespace. \n   Here we need to provide the namespace name.\n3. Rebuild DLL and add reference to project.	0
16644071	16643908	How to filter / selectively copy values from one DataGridView to another DataGridView	var results = new List<Products>(); //our new data source with only checked items\n\nforeach (DataGridViewRow row in productsDataGridView.Rows)\n{\n    var item = row.DataBoundItem as Products; //get product from row (only when grid is databound!)\n\n    if (item.Promotions > 0)\n    {\n        results.Add(item);        \n    }\n}\n\npromotionsDataGridView.DataSource = results;	0
11321219	11149422	How to get selected rows text in the specific cell?	SchoolDepartment newPerson = rows[rows.Count - 1];\nMessageBox.Show(newPerson.ID.ToString());	0
20604850	20604714	Turning strings into commands?	using System;\n\nnamespace ConsoleApplication1\n{\n    enum ButtonChanger\n    {\n        Change1 = 1,\n        Change2 = 2,\n        Change3 = 3\n    }\n\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            var changer = GetButtonChanger(2);\n\n            Console.WriteLine(changer);\n            Console.WriteLine((int)changer);\n        }\n\n        private static ButtonChanger GetButtonChanger(int i)\n        {\n            return (ButtonChanger)Enum.Parse(typeof(ButtonChanger), string.Format("Change{0}", i));\n        }\n    }\n}	0
12921145	12921088	Populating data in dropdown menu	CustomService custsrv = new CustomService();\nList<Code> dept = custsrv.GetDepartment(true);	0
10493744	10493699	C#: how to pass mathematical function from textbox to function	var ev = \n    new Eval3.Evaluator(\n        Eval3.eParserSyntax.c,/*caseSensitive*/ \n        false);\n\nMessageBox.Show(ev.Parse("1+2+3").value.ToString());	0
32881035	32880888	Passing data from thickbox popup to parent through querystring	function CloseDialog(tanksize,companyID, accountID, address, serviceContract, cod, divisionId) {\n    tb_remove();\n    var url = 'ServiceTicket.aspx?CompanyID=' + companyID + '&AccountID=' + accountID + '&Address=' + address.replace('#', '%23') + '&TankSize=' + tanksize + '&divisionId=' + divisionId;    \n    window.parent.location.href = url;\n}	0
11627092	11625344	DevExpress GridControl line numbers	var col = gridView1.Columns.Add();\ncol.FieldName = "counter";\ncol.Visible = true;\ncol.UnboundType = DevExpress.Data.UnboundColumnType.Integer;\ngridView1.CustomUnboundColumnData += gridView1_CustomUnboundColumnData;\n\nvoid gridView1_CustomUnboundColumnData(object sender, DevExpress.XtraGrid.Views.Base.CustomColumnDataEventArgs e)\n{\n    if (e.IsGetData)\n        e.Value = e.ListSourceRowIndex+1;\n}	0
3568501	3568318	Make a Backup Utility in C#	string[] d = Directory.GetDirectories(@"C\", "*.*", SearchOption.TopDirectoryOnly);\nDirectoryInfo[] di = new DirectoryInfo[d.Length];\nfor (int x = 0; x < d.Length; x++)\n{\n    di[x] = new DirectoryInfo(d[x]);\n}	0
10907771	10907354	WPF ComboBox Bind SQL with selectedValue as in database	this.combobox.SelectedValue = Table2ID;	0
1175020	1174960	Is there a way to paint semi transparently on a PictureBox?	Color c = Color.FromArgb(128, Color.Blue);\nusing (Brush b = new SolidBrush(c))\n{\n  e.Graphics.FillRectangle(b, 0, 0, 50, 50);\n}	0
310022	303656	Open new Page from an Xbap	private void ShowPage(Page page)\n{\n    NavigationWindow popup = new NavigationWindow();  \n    popup.Height = 400;\n    popup.Width = 600;\n    popup.Show();\n    popup.Navigate(page);\n}	0
3265449	3265257	Getting all changes made to an object in the Entity Framework	var myObjectState=myContext.ObjectStateManager.GetObjectStateEntry(myObject);\nvar modifiedProperties=myObjectState.GetModifiedProperties();\nforeach(var propName in modifiedProperties)\n{\n    Console.WriteLine("Property {0} changed from {1} to {2}", \n         propName,\n         myObjectState.OriginalValues[propName],\n         myObjectState.CurrentValues[propName]);\n}	0
15470010	14975932	How to programmatically add colored border to a cell in c# excel vsto?	range.Borders.LineStyle = Excel.XlLineStyle.xlDot;\nrange.Borders.Color = ColorTranslator.ToOle(Color.Red);	0
6866975	6866939	I need help with C# operators	conditionX ^conditionY	0
7918903	7918706	Apply custom attributes to properties programmatically	[MetadataType(typeof(IMyAttributes))\npublic DerivedClass : BusinessClass\n{\n}\n\npublic interface IMyAttributes\n{\n  [Required]\n  public string Name { get; set; }\n}	0
16455563	16455541	Is it possible to bind multiple datatables to a listview?	DataTable merged = new DataTable(); \nmerged.Merge(table1); \nmerged.Merge(table2);\nmerged.Merge(table3);\n//Merge the rest of the data tables.\nlvMyList.DataSource = merged;\nlvMyList.DataBind();	0
11203402	11201878	Normalize phone numbers using regex	List<string> oldlist = new List<string>();\nList<string> newlist = new List<string>();\nforeach(string s in oldlist)\n{\n     if(s.Contains('(')) s = s.Replace('('), "");//etc\n     newlist.Add(numFormat(s));\n}\n\nstring prefix = "495";\n\nstring numFormat(string s)\n{\n     string my;\n     if(s.Length == 7)\n     {\n         my = string.Format("+7 ({0}) {1} {2} {3}", prefix, s.substring(0,3), s.subtring(3,2), s.substring(5,2);\n     }\n     else if(s.length == 10)\n     {\n         my = string.Format("+7 ({0}) {1} {2} {3}", s.substring(0,3), s.substring(3,3), s.subtring(5,2), s.substring(7,2);        \n     }\n     //etc\n     return my;\n}	0
4623773	4623727	Redirecting to a page with #placeholder	Response.Redirect(string.Format("{0}?ReturnUrl={1}#{2}",\n   Server.Encode(path), Server.Encode(path), placeholder))));	0
21727895	21726405	Binary representation of an enum in protobuf-net	[Flags]	0
3836706	3836688	String to Date parsing in C#?	DateTime when = DateTime.ParseExact("20101001151014", "yyyyMMddHHmmss",\n    CultureInfo.InvariantCulture);	0
5102892	5102865	ASP.net load XML file from URL	protected void Page_Load(object sender, EventArgs e)\n{\n\n    XmlDocument xdoc = new XmlDocument();//xml doc used for xml parsing\n\n    xdoc.Load(\n        "http://latestpackagingnews.blogspot.com/feeds/posts/default"\n        );//loading XML in xml doc\n\n    XmlNodeList xNodelst = xdoc.DocumentElement.SelectNodes("entry");//reading node so that we can traverse thorugh the XML\n\n    foreach (XmlNode xNode in xNodelst)//traversing XML \n    {\n        litFeed.Text += "read";\n    }\n\n}	0
6738701	6686545	How do you create a page using the API for sharepoint 2010?	private void createPage()\n    {\n        ClientContext context = new ClientContext(URL);\n        Site siteCollection = context.Site;\n        Web site = context.Web;\n\n        List pages = site.Lists.GetByTitle("Site Pages");\n\n        Microsoft.SharePoint.Client.\n        FileCreationInformation fileCreateInfo = new FileCreationInformation();\n        fileCreateInfo.Url = "NewPage.aspx";\n        context.Load(pages.RootFolder.Files.Add(fileCreateInfo));\n\n        context.ExecuteQuery();\n        context.Dispose();\n    }	0
17512322	17512260	Get string from html with Regex	var dives = from div in htmlDoc.DocumentNode.Descendants("div")\n           where div.Id == "div_space" \n           select div;	0
10863146	10863064	An exam exercise about swapping items in an array in C#	int iterationsNum = (finish - start) / 2 ;\nfor(int i=0;i<=iterationsNum;i++)\n{\n    if(start+i != finish-i)\n    {\n      swap(values, start+ i, finish-i);\n    }\n}	0
8620822	8619066	Show datatable in GridView	int rowCount = (SP1 as DataTable).Rows.Count;	0
12037508	12017290	IsolatedStorage in Window Phone 7.5	String sb;\n\n        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())\n        {\n            if (myIsolatedStorage.FileExists(fileName))\n            {\n                StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, myIsolatedStorage));\n\n                sb = reader.ReadToEnd();\n\n                reader.Close();\n            }\n\n            if(!String.IsNullOrEmpty(sb))\n            {\n                 MessageBox.Show(sb);\n            }\n        }	0
13156960	13148825	Validating enums with a custom FluentValidator validator	IsInEnum()	0
6289560	6289489	change between 'and' and 'or' filter in linq-to-xml in c#	var filters = chkBx.Where(r => r.Checked).Select(r => r.Text).ToList();\nselectedElements = selectedElements.Where(r =>\n      filters.Contains((string)r.Parent.Element(element)))	0
8704499	8704412	Add a conditional clause to Delete a table's rows matching a list's items	var sbSql = new System.Text.StringBuilder(500);\n\nsbSql.Append("delete from X where id in (");\n\nif (lstItem.Count != 0) {\n  foreach (int value in lstItem)\n  {\n     if (sbSql.Length != 0) \n     {\n        sbSql.Append(",");\n     }\n     sbSql.Append(value);\n  }\n\n} else {\n   sbSql.Append(-1);\n}\n\nsbSql.Append(")");\n\nSqlComm.CommandText = sbSql.ToString();	0
5937276	5937119	Sending AT Command to a USB-Connected GPRS Modem in C#	System.IO.Ports.SerialPort	0
4294978	4294951	C#: Using a referenced DLL	using <Namespace of MyClass>;\n\npublic static void Main()\n{\n   MyClass blah = new MyClass();\n}	0
23103212	23087396	EventLogQuery - How do I filter off certain events?	*[System[(Level=1 or Level=2) and (ErrorID!=1001)]]	0
29226257	29225207	How to fill all dates of selected month in DataTable	public DataTable GetDates()\n    {\n        DataTable dt = new DataTable();\n        dt.Columns.Add("Date", typeof(DateTime));\n\n        int year = Convert.ToInt32(ddyear.SelectedItem.Value);\n        int month = Convert.ToInt32(ddmonth.SelectedItem.Value);\n\n        int daysInMonth = DateTime.DaysInMonth(year, month);\n        for (int i = 0; i < daysInMonth; i++)\n        {\n            DataRow dr = dt.NewRow();\n            dr["Date"] = new DateTime(year, month, i + 1);\n            dt.Rows.Add(dr);\n        }\n\n        return dt;\n    }	0
15459870	15459844	How to Union child collections from their parent entities in EF?	var query = (from p in parents\n             from c in p.Children\n             select c)\n            .Distinct();	0
19650379	19649420	RegularExpressions with C#	String s = "[TEST name1=\"smith ben\" name2=\"Test\" abcd=\"Test=\" mmmm=\"Test=\"]";\n\nSortedList<string, string> list = new SortedList<string, string>();\n\n//Remove the start and end tags\ns = s.Remove(0, s.IndexOf(' '));\ns = s.Remove(s.LastIndexOf('\"') + 1);\n\n//Split the string\nstring[] pairs = s.Split(new char[] { '\"' }, StringSplitOptions.None);\n\n//Add each pair to the list\nfor (int i = 0; i+1 < pairs.Length; i += 2)\n{\n   string left = pairs[i].TrimEnd('=', ' ');\n   string right = pairs[i+1].Trim('\"');\n   list.Add(left, right);\n}	0
6137130	6137100	ASP.NET Replace a double quote with html number	InputString = InputString.Replace("\"", "&#34;");	0
21096661	21096550	Does EF CodeFirst create any Temp tables by default?	CREATE TABLE	0
18013494	18013066	Playback.Encrypt how to decrypt C# CodedUI	Password.Encrypt()	0
7146271	7146025	getting two column values from same table depending on the condition	(from categorytable in tsg.categories\nwhere categorytable.category_Id == categoryids\nselect new {Name=categorytable.category_Name, \n            Description=categorytable.category_Description}).SingleOrDefault();	0
2426912	2426885	Need to parse a string till the end of the file	StreamReader reader = File.OpenText(filename);\n    string line = null\n    while ((line = reader.ReadLine()) != null)\n    {\n    // ... your stuff here\n    }\n    reader.Close();\n    reader.Dispose();	0
20680781	20680372	Incrementing an int during insert	string sql = "INSERT INTO tblTarget (target,ref) " + \n             "SELECT ?, MAX(ref)+1 FROM tblTarget";\nOleDbCommand cmd = new OleDbCommand(sql, conn);\ncmd.Parameters.AddWithValue("@target", TextTitle.Text);\ncmd.ExecuteNonQuery();	0
34236164	34236096	How can i find the last written image to hard disk in a directory but only types of jpg and raw?	public void DisplayLastTakenPhoto()\n    {\n        var directory = new DirectoryInfo(@"C:\temp");\n        var myFile = directory.EnumerateFiles()\n         .Where(f => f.Extension.Equals(".js", StringComparison.CurrentCultureIgnoreCase) || f.Extension.Equals("raw", StringComparison.CurrentCultureIgnoreCase))\n         .OrderByDescending(f => f.LastWriteTime)\n         .First();\n        Assert.IsNotNull(myFile);\n    }	0
14247501	14094857	remove a condition from ef expression tree	var orders = db.Orders.Where( ord => \n    (isFirstConditionRelevant && ord.Channel == 1) \n    || (isSecondConditionRelvant && ord.Channel == 2));	0
17691586	17691499	How to read all folder's name in desktop?	var names = new DirectoryInfo(Environment.GetFolderPath(Environment.SpecialFolder.Desktop))\n            .GetDirectories().Select(d => d.Name).ToList();	0
32851691	32851488	Inserting into an index position in a List	public double this[int i]\n{  \n    get\n    {\n        int index = i - 1;\n        if (index < 0 || index >= scores.Count)\n        {\n            throw new Exception("Invalid CA number get");\n        }\n        else\n            return scores[i]; \n    }\n    set\n    {\n        int index = i - 1;\n        if (index < 0 || index > scores.Count)\n        {\n            throw new Exception("Invalid CA number set");\n        }\n        else\n        { \n            if (index < scores.Count)\n                scores[index] = value;\n            else\n                scores.Add(value);\n        }\n    }\n}	0
2556737	2509885	C#.NET : A graphical control makes my app freeze after workstation unlock	ShowDialog()	0
4983014	4982996	Good implementation of a Change Calculator in C#	const int LARGE_PACK = 1000;\nconst int MEDIUM_PACK = 200;\nconst int SMALL_PACK = 20;\n\nint largePacks = (int)(Amount / LARGE_PACK);\nint mediumPacks = (int)((Amount % LARGE_PACK) / MEDIUM_PACK);\nint smallPacks = (int)ceil(((float)((Amount % LARGE_PACK) % MEDIUM_PACK) / SMALL_PACK));	0
6174738	5528895	NHibernate QueryOver Select only needed model	var qOverInclude = QueryOver.Of<MyModel>(() => mModel)\n                .JoinAlias(() => mModel.MyList, () => mList, JoinType.LeftOuterJoin)\n                    .Where(() => mList.ID == myID)\n                    .And(() => mList.Type == myType)\n                .Select(x => x.IdMyModel);\n\n  var qOver = _HibSession.QueryOver<MyModel>(() => mModel)\n                .JoinAlias(() => mModel.MyDescription, () => mDescription, JoinType.LeftOuterJoin)\n                .Where(() => mDescription.IDLanguage == myLanguage)\n                .WithSubquery.WhereProperty(() => mModel.IdMyModel).In(qOverSubQuery)\n                .OrderByAlias(() => mModel.IdMyModel).Asc\n                .Future<MyModel>();	0
12303067	12301908	how to use elim-quantifiers using .net API in Z3?	// (exists ((x Int)) (and (< t1 x) (< x t2))))\nContext z3 = new Context();\nExpr t1 = z3.MkIntConst("t1");\nExpr t2 = z3.MkIntConst("t2");\nExpr x = z3.MkIntConst("x");\n\nExpr p = z3.MkAnd(z3.MkLt((ArithExpr)t1, (ArithExpr)x), z3.MkLt((ArithExpr)x, (ArithExpr)t2));\nExpr ex = z3.MkExists(new Expr[] { x }, p);\n\nGoal g = z3.MkGoal(true, true, false);\ng.Assert((BoolExpr)ex);\nTactic tac = Instance.Z3.MkTactic("qe"); // quantifier elimination\nApplyResult a = tac.Apply(g); // look at a.Subgoals	0
12945821	12933623	Portability worries because of custom cursor path in C#	var info = Application.GetResourceStream(new Uri("pack://application:,,,/Images/hand2.cur"));\nvar cursor = new Cursor(info.Stream);	0
26794182	26534959	How to terminate windows phone 8.1 app	Application.Current.Exit()	0
3399399	3396084	Scope of a feature activated Custom Sharepoint-Timer Job	public override void Execute(Guid targetInstanceId)\n    {\n        foreach (SPSite site in this.WebApplication.Sites)\n        {\n            try\n            {\n                if (SPSite.Exists(new Uri(site.Url)) && null != site.Features[FeatureId.AlertMeJob])\n                {\n                    try\n                    {\n                        ExecuteJob(site);\n                    }\n                    catch (Exception ex)\n                    {\n                        // handle exception\n                    }\n                }\n            }\n            finally\n            {\n                site.Dispose();\n            }\n        }\n    }	0
14467374	14023499	How To Get the ID for Uploaded Video to YouTube Using Resumable Upload	ru.AsyncOperationCompleted += new AsyncOperationCompletedEventHandler(ru_AsyncOperationCompleted);\n\nvoid ru_AsyncOperationCompleted(object sender, AsyncOperationCompletedEventArgs e)\n        {\n\n            //upload complete\n            YouTubeRequestSettings ytSettings = new YouTubeRequestSettings("myApp", googleDevKey, ytUsername, ytPassword);\n            Video v = ytRequest.ParseVideo(e.ResponseStream);\n            string videoId = v.VideoId;\n            string watchPage = v.WatchPage.ToString();\n\n        }	0
24138520	24138441	How to properly do a template of a templated class?	public class SparseGraphPathFinder : PathFinder<SparseGraph<ConcreteNode, ConcreteEdge>, ConcreteNode, ConcreteEdge>\n{\n\n}	0
320325	320281	Determine number of pages in a PDF file	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing iTextSharp.text.pdf;\nusing iTextSharp.text.xml;\nnamespace GetPages_PDF\n{\n  class Program\n{\n    static void Main(string[] args)\n      {\n       // Right side of equation is location of YOUR pdf file\n        string ppath = "C:\\aworking\\Hawkins.pdf";\n        PdfReader pdfReader = new PdfReader(ppath);\n        int numberOfPages = pdfReader.NumberOfPages;\n        Console.WriteLine(numberOfPages);\n        Console.ReadLine();\n      }\n   }\n}	0
11138981	11138584	Url Encoding method for Special Character  in c#	System.Text.UnicodeEncoding uni = new UnicodeEncoding();\nbyteArray = uni.GetBytes(data);	0
15017194	15017132	How to Send Email With Attachment In Asp.Net	// create attachment and set media Type\n//      see http://msdn.microsoft.com/de-de/library/system.net.mime.mediatypenames.application.aspx\nAttachment data = new Attachment(\n                         "PATH_TO_YOUR_FILE", \n                         MediaTypeNames.Application.Octet);\n// your path may look like Server.MapPath("~/file.ABC")\nmessage.Attachments.Add(data);	0
32297651	32297621	Can't run a simple WinForms app, shows a default unchanged form	public Form1()\n  {\n        InitializeComponent();\n  }	0
9162799	9162714	Sqlite null dataset even if there is data in datatable.rows	var ds = new DataSet();\n\nmycommand.CommandText = sql;\nSQLLiteDataAdapter adapter = new SQLLiteDataAdapter(mycommand);\nadapter.Fill(ds);	0
15669497	15669301	ASP.net with C# where to add a method for list box that is the total price of each cartitem (Unit price * quantity)	public string Display()\n{\n    return cproduct.Description + " (" + cquantity.ToString() + " at " + cproduct.UnitPrice.ToString("c") + " each) Total  " + (cquantity*cproduct.UnitPrice).ToString("c") ;\n}	0
1663583	1663512	Multiple from clauses in LINQ	Enumerable.Range(1, 3).SelectMany(\n    i => Enumerable.Range(4, 3),\n    (i, j) => new Tuple<int, int>(i, j)\n).ToList();	0
16691653	16691554	Replace word/value in text with dynamic number	Random rand = new Random();\ntext = Regex.Replace(text, @"{Rand_num (.+?)-(.+?)}", match => {\n    int from = int.Parse(match.Groups[1].Value),\n        to = int.Parse(match.Groups[2].Value);\n    // note end is exclusive\n    return rand.Next(from, to + 1).ToString();\n});	0
10044637	10044603	Int to Decimal Conversion - Insert decimal point at specified location	int i = 7122960;\ndecimal d = (decimal)i / 100;	0
17469507	17469349	Mapping columns in a DataTable to a SQL table with SqlBulkCopy	public void BatchBulkCopy(DataTable dataTable, string DestinationTbl, int batchSize)\n{\n    // Get the DataTable \n    DataTable dtInsertRows = dataTable;\n\n    using (SqlBulkCopy sbc = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.KeepIdentity))\n    {\n        sbc.DestinationTableName = DestinationTbl;\n\n        // Number of records to be processed in one go\n        sbc.BatchSize = batchSize;\n\n        // Add your column mappings here\n        sbc.ColumnMappings.Add("field1","field3");\n        sbc.ColumnMappings.Add("foo","bar");\n\n        // Finally write to server\n        sbc.WriteToServer(dtInsertRows);\n    }    \n}	0
20760173	20760036	Getting two new tabs on one click of button in tab control	private bool addingPage = false;\n\n....\n\n\n private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)\n {\n    if(!addingPage)\n    {\n        addingPage = true;\n        TabPage tab = new TabPage("New Tab");\n        tabControl1.TabPages.Insert(tabControl1.TabPages.Count - 1,tab);\n        tabControl1.SelectedTab = tab;\n        addingPage = false;\n    }\n }	0
16780431	16746290	How do I update a listview when my variable changes?	public static readonly DependencyProperty HighlightedProperty = DependencyProperty.Register("highlightedIndex", typeof(int), typeof(MyListView), new PropertyMetadata(null, propertyChanged));\n\n\n    private static void propertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n    {\n\n        int newValue = (int)e.NewValue;\n        ListView lv = (ListView)d;\n\n        foreach (ListViewItem lvi in lv.Items)\n        {\n            if (lv.Items.IndexOf(lvi) == newValue)\n            {\n                lvi.Background = new SolidColorBrush(Colors.LightGreen);\n            }\n            else\n            {\n                lvi.Background = new SolidColorBrush();\n            }\n        }\n    }	0
19831961	19831913	copying values of a dataTable to another DataTable with different clumns	foreach (DataRow sourcerow in dt1.Rows)\n{\n    DataRow destRow = dt2.NewRow();\n    destRow["ID"] = sourcerow["PRODUCT_ID"];\n    destRow["MIN"] = sourcerow["MIN_VALUE"];\n    destRow["MAX"] = sourcerow["MAX_VALUE"];\n    destRow["POINT_TO_ADD"] = sourcerow["AMOUNT"];\n    dt2.Rows.Add(destRow);\n}	0
8639565	8625357	Wintellect PowerCollections for Windows 7 Phone?	/// <summary>\n/// This is a dummy attribute to support silverlight\n/// </summary>\n/// <remarks></remarks>\npublic class Serializable : Attribute\n{\n    public Serializable() : base()\n    {\n    }\n}	0
17903331	17903298	C# Console application two main()	public class MyClass\n{\n    public void MyMethod()\n    {\n        //code goes here\n    }\n}	0
4377790	4375190	Changing IsNewRow status to false in DataGridView or Simulating keystroke on a cell	switch (e.KeyData)\n  {\n    case Keys.F6: //Copy the row above.\n      if (MyGridView.NewRowIndex > 0 && MyGridView.NewRowIndex == rowIndex)\n      {\n        int colIndex = MyGridView.CurrentCell.ColumnIndex;\n\n        MyGridView.Rows.Add();\n        MyGridView.CurrentCell = MyGridView.Rows[rowIndex].Cells[colIndex];\n\n        MyGridView.CurrentRow.Cells[CustomColumn.Index].Value\n          = MyGridView.Rows[rowIndex - 1].Cells[Customer.Index].Value;\n\n        MyGridView.CurrentRow.Cells[DateColumn.Index].Value\n          = MyGridView.Rows[rowIndex - 1].Cells[DateColumn.Index].Value;\n\n        MyGridView.CurrentRow.Cells[RefColumn.Index].Value\n          = MyGridView.Rows[rowIndex - 1].Cells[RefColumn.Index].Value;\n       }\n  }	0
2728441	2728321	How to parse string with hours greater than 24 to TimeSpan?	string span = "35:15";\nTimeSpan ts = new TimeSpan(int.Parse(span.Split(':')[0]),    // hours\n                           int.Parse(span.Split(':')[1]),    // minutes\n                           0);                               // seconds	0
8269554	8260322	Filter a Treeview with a Textbox in a C# winforms app	void fieldFilterTxtBx_TextChanged(object sender, EventArgs e)\n{\n    //blocks repainting tree till all objects loaded\n    this.fieldsTree.BeginUpdate();\n    this.fieldsTree.Nodes.Clear();\n    if (this.fieldFilterTxtBx.Text != string.Empty)\n    {\n        foreach (TreeNode _parentNode in _fieldsTreeCache.Nodes)\n        {\n            foreach (TreeNode _childNode in _parentNode.Nodes)\n            {\n                if (_childNode.Text.StartsWith(this.fieldFilterTxtBx.Text))\n                {\n                    this.fieldsTree.Nodes.Add((TreeNode)_childNode.Clone());\n                }\n            }\n        }\n    }\n    else\n    {\n        foreach (TreeNode _node in this._fieldsTreeCache.Nodes)\n        {\n            fieldsTree.Nodes.Add((TreeNode)_node.Clone());\n        }\n    }\n    //enables redrawing tree after all objects have been added\n    this.fieldsTree.EndUpdate();\n}	0
26084841	25836173	How to seed new junction table	modelBuilder.Entity<Product>()\n    .HasMany(x => x.Clients)\n    .WithMany(x => x.Products)\n.Map(x =>\n{\n    x.ToTable("UserPriceList"); // third table is named Cookbooks\n    x.MapLeftKey("ProductId");\n    x.MapRightKey("ClientId");\n});	0
17884482	17883402	Iterate over a list that contains a self-referencing list	public static IEnumerable<T> Traverse<T>(this IEnumerable<T> source, Func<T, IEnumerable<T>> fnRecurse)\n    {\n        foreach (T item in source)\n        {\n            yield return item;\n\n            IEnumerable<T> seqRecurse = fnRecurse(item);\n\n            if (seqRecurse != null)\n            {\n                foreach (T itemRecurse in Traverse(seqRecurse, fnRecurse))\n                {\n                    yield return itemRecurse;\n                }\n            }\n\n        }\n    }	0
33685703	33685505	How to convert JSON to BSON using Json.NET	using Newtonsoft.Json.Bson;\nusing Newtonsoft.Json;\n\n class Program\n    {\n        public class TestClass\n        {\n            public string Name { get; set; }\n        }\n\n        static void Main(string[] args)\n        {\n            string jsonString = "{\"Name\":\"Movie Premiere\"}";\n            var jsonObj = JsonConvert.DeserializeObject(jsonString);\n\n            MemoryStream ms = new MemoryStream();\n            using (BsonWriter writer = new BsonWriter(ms))\n            {\n                JsonSerializer serializer = new JsonSerializer();\n                serializer.Serialize(writer, jsonObj);\n            }\n\n            string data = Convert.ToBase64String(ms.ToArray());\n\n            Console.WriteLine(data);\n        }\n    }	0
32659789	32659693	Sort List by Value of SubList with where clause LINQ	var result= foo.OrderByDescending(x => x.PairList[1].Value);	0
18562566	18562555	Negating a variable shortcut	x ^= true;	0
3802538	3802509	UpperCase display in a Textbox	#idOfyourTextbox{\n      text-transform: uppercase;\n  }	0
15546955	15546536	How to make a gallery lock Application in windows phone 8?	Isolated Storage	0
8197336	8197294	How to download an image using a URL with a query string instead of image path?	using (WebClient Client = new WebClient ())\n{\n    Client.DownloadFile("http://www.mywebsite.com/img.aspx?imgid=12345", "12345.jpg");\n}	0
6571828	6571798	Pick out a group of items using linq to xml	// TODO: Work out what to do if there are zero or multiple such elements\nvar columns = xdoc.Descendants("property")\n                  .Where(x => (string) x.Attribute("name") == "Columns")\n                  .Single();\n\nvar items = columns.Elements("property");\n\nforeach (var item in items)\n{\n    Console.WriteLine("Item {0}", (string) item.Attribute("name"));\n    foreach (var property in items.Elements("property"))\n    {\n        Console.WriteLine("  {0} = {1}", (string) item.Attribute("name"),\n                          (string) item);\n    }\n}	0
7626452	7626386	C# grade array with histogram	For(j=1; j<11; j++)\n{\n    StringBuilder ab = new StringBuilder(grades[j]);\n    For(int i=0; i<grades[j]; i++)\n    {\n        sb.Append(" *");\n    }\n\n    Console.WriteLine("Student {0} has grade {1} : {2}", j, grades[j], sb.ToString());\n\n}	0
11210809	11210354	Unloading image from picturebox if string matches	private void button2_Click(object sender, EventArgs e)     \n{    \n     if(listbox2.SelectedIndex >= 0)\n     {\n         string curItem = listBox2.Items[listbox2.SelectedIndex].ToString();\n         if(curItem == "SomeOtherString")\n         {\n             listBox2.Items.RemoveAt(listBox2.SelectedIndex);      \n             picturebox.Image.Dispose();\n             picturebox.Image = null; // Not really necessary\n         }\n     }\n}	0
3123047	3123014	How to convert this recursive code to Linq	static int MyMethod(MyClass my, bool b)\n{\n  int cnt = my.SomeMethod().Sum(cls => cls.length);    \n  if (b)\n  {\n      cnt += my.SomeOtherMethod().Sum(aa => MyMethod(aa, true));\n  }    \n  return cnt;\n}	0
2039026	2038896	Adding an Array of labels to a Panel	labels[index].Size = new Size(50, 12);	0
19545612	19466991	write a loop that prints a number of lines the user entered into the text box, this is using c# windows application	private void button1_Click(object sender, EventArgs e)\n    {\n        int OutputNumber;  \n        bool number = Int32.TryParse(inputtxt.Text, out OutputNumber);\n        string[] array = new string[OutputNumber];\n        int put = 0;\n        for (int i = 0; i < array.Length; i++)\n        {\n\n            array[i] = put.ToString();\n            put++;\n\n            string result = ConvertStringArrayToString(array);\n            string result1 = result + OutputNumber.ToString();\n            outputtxt.Text = result1;\n        }}\n\n            static string ConvertStringArrayToString(string[] array)\n        {\n\n            StringBuilder buildingstring = new StringBuilder();\n            foreach (string value in array)\n            {\n                buildingstring.Append(value);\n                buildingstring.Append("\r\n");\n            }\n            return buildingstring.ToString();\n}	0
27074781	27074480	Filter words of a collection by characters typed in text box and show the resulting words in a listbox	// Get the words in the dictionary starting with the textbox text.\nvar matching = sortedDic.Keys.Where(x => x.StartsWith(searchText.Text)).ToList();\n\n\n// Assign the values to the listbox.\nlistboxWords1.Items.AddRange(matching);	0
29088481	29087947	Unhandled DivideByZero exception from an external DLL - C#	using System;\nusing System.Security.Permissions;\n\npublic class Test\n{\n\n   [SecurityPermission(SecurityAction.Demand, Flags = SecurityPermissionFlag.ControlAppDomain)]\n   public static void Example()\n   {\n       AppDomain currentDomain = AppDomain.CurrentDomain;\n       currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler);\n\n       try\n       {\n          throw new Exception("1");\n       }\n       catch (Exception e)\n      {\n         Console.WriteLine("Catch clause caught : " + e.Message);\n      }\n\n      throw new Exception("2");\n\n      // Output: \n      //   Catch clause caught : 1 \n      //   MyHandler caught : 2\n   }\n\n  static void MyHandler(object sender, UnhandledExceptionEventArgs args)\n  { \n     Exception e = (Exception)args.ExceptionObject;\n     Console.WriteLine("MyHandler caught : " + e.Message);\n  }\n\n  public static void Main()\n  {\n     Example();\n  }\n\n}	0
26215746	26099214	Unable to convert MongoCursor to BsonDocument	MongoDatabase db = MdbServer.GetDatabase(strDbName);\n                        MongoCollection<BsonDocument> collection = db.GetCollection(strCollectionName);                          \n\n                        foreach (var document in collection.Find(query).SetFields(Fields.Include(includeFields).Exclude("_id")))\n                        {\n                            foreach (string name in document.Names)\n                            {\n                                BsonElement element = document.GetElement(name);\n                                BsonValue value = document.GetElement(name).Value;\n                                bsonDoc.Add(element.Name, value);\n                            }\n                        }	0
5872837	5872764	Is there a way to set a file extension when pushing a dynamically created file?	Response.AddHeader("content-disposition", "attachment; filename=SomeName.pdf");	0
8676898	8676745	assigning input values to cmdmysql.Parameters.Add using arrays	cmdmysql.Parameters.AddWithValue("@_maxvalue", words[0]);	0
6747988	6747810	How to remove underline of specific link cells in DataGridView	DataGridViewLinkCell linkCell = dcell as DataGridViewLinkCell\nif(linkCell != null)\n//your code...	0
17561198	17561138	DateTime from C# an hour late?	var span = (DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalSeconds;\n\nreturn span;	0
32742196	32741924	How Do I Properly Determine User File System Permissions for a File?	if ((FileSystemRights.Write & fsar.FileSystemRights) != FileSystemRights.Write) \n    return false;\n\nreturn true;	0
4987803	4987738	Re attempt server connection after some time	class MyClass\n    {\n\n\n\n\n System.Timers.Timer m_ConnectTimer = null;\n\n        ..\n        ..\n\n    void ConnecToServer()\n    {\n        if (m_ConnectTimer != null)\n        {\n            m_ConnectTimer.Enabled = false;\n            m_ConnectTimer.Dispose();\n            m_ConnectTimer = null;\n        }\n\n        //Try to connect to the server\n\n        if (bConnectedToTheServer)\n        {\n            //Do the servery stuff\n        }\n        else //set the timer again\n        {\n            m_ConnectTimer = new Timer(30 * 60 * 1000);\n            m_ConnectTimer.Elapsed += new ElapsedEventHandler(TimerHandler)\n            m_ConnectTimer.Enabled = true;\n        }\n\n    }\n\n\n    void TimerHandler(object sender, ElapsedEventArgs e)\n    {\n        ConnectToServer();\n    }\n\n}	0
12851871	12843007	Get Farm Features from SharePoint 2010	foreach (SPFeatureDefinition feature in SPFarm.Local.FeatureDefinitions)\n{\n    if (feature.Scope = "Farm")\n    {\n        string featureName = feature.DisplayName;\n        if (featureName != null)\n        {\n            XElement newItem = new XElement("Item", featureName);\n            infoTree.Add(newItem);\n        }\n    }	0
24705088	24705030	C# How to make a factory method return of the subclass type	public class BankAccount<T> where T : BankAccount<T>, new()\n{\n    public T SomeFactoryMethod() { return new T(); }\n}\n\npublic class SavingsAccount: BankAccount<SavingsAccount>{}	0
30373364	30371149	Set scroll to end of Image (change default value)	HorizontalScrollView scrollView1 = new HorizontalScrollView(this);\nvar handler = new Handler();\nhandler.PostDelayed (() => scrollView1.FullScroll (FocusSearchDirection.Right), 100);	0
26840963	26840818	How to identify a presentation in PowerPoint?	Application.ActiveWindow	0
21701970	21701770	Get result from InputPrompt in Coding4Fun toolkit	void input_completed(object sender, PopUpEventArgs<string, PopUpResult> e)\n{\n    string result = e.Result;\n}	0
17585811	17585758	Naming Conventions for parameters in C#	private static Call AddLog(NewCallEventArgs ev, Call previousCall)\n{\n    var newCall = new Call\n    {\n    }\n    return newCall;\n}	0
20995840	20995673	How to loop through an array of parameters and relate them to each other	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Threading.Tasks;\n\nnamespace Payments\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            Payment p1 = new Payment();\n            Payment p2 = new Payment();\n            Payment p3 = new Payment();\n\n            Payment Sorted = SortPayments(p1, p2, p3);\n        }\n\n        static private Payment SortPayments(params Payment[] payments)\n        {\n            if(payments.Length == 0)\n            {\n               return null;\n            }\n\n            Payment FirstPayment = payments[0];\n\n            Payment current = FirstPayment;\n            for (int i = 1; i < payments.Length; i++ )\n            {\n                current.SupplementalPayment = payments[i];\n                current = current.SupplementalPayment;\n            }\n\n            return FirstPayment;\n        }\n    }\n}	0
13615013	13614972	C# Delete the nth item from a string	var removed = s.Remove(1, 1);	0
5716838	5716799	Multiple interfaces contained in one List<T>	class MyList<T> : List<T>\n  where T : myObjectBase, IDisposable, IClonable\n{\n}	0
27140897	27140815	How to Convert string "00h:03m:30s:793ms" to TimeSpan in c#	TimeSpan.TryParseExact(\n    "00h:03m:30s:793ms",\n    "hh'h:'mm'm:'ss's:'fff'ms'",\n    CultureInfo.InvariantCulture,\n    out testCaseData.duration);	0
31156226	31155932	How to add hyperlink in RegisterStartupScript or in alert message?	var link = "https://www.google.com"\nvar result = confirm("Do you want to navigate to: " + link + "?");\nif (result)\n{\n    window.location = link;   \n}	0
8691367	8687066	How can I count the online users in my application?	void Application_Start(object sender, EventArgs e) {\n    Application["OnlineUsers"] = 0;\n}\n\nvoid Session_Start(object sender, EventArgs e) {\n    Application.Lock();\n    Application["OnlineUsers"] = (int)Application["OnlineUsers"] + 1;\n    Application.UnLock();\n}\n\nvoid Session_End(object sender, EventArgs e) {\n    Application.Lock();\n    Application["OnlineUsers"] = (int)Application["OnlineUsers"] - 1;\n    Application.UnLock();\n}	0
27772161	27713435	How to use a C++ dll in Windows Phone 8.1 XAML App within C++ Runtime Component	copy to output directory	0
32581839	32581339	Find the parenthesis pair () within a list of parenthesis	public static Dictionary<int,int> GetPair(List<Token> data)\n{\n    var pair = new Dictionary<int, int>();\n\n    var stack = new Stack<Token>();\n    foreach (var item in token)\n    {\n        if (item.TokenValue == "(")\n        {\n            stack.Push(item);\n            continue;\n        }\n\n        if (item.TokenValue == ")")\n        {\n            var starting = stack.Pop();\n            pair.Add(starting.TokenId, item.TokenId);\n        }\n    }\n\n    return pair;\n}	0
19691237	19691027	What time format is this, and how to get it from DatetimePicker	yyyy-MM-ddTHH:mm:ss.fffzzz	0
17432643	17431585	Decode Xdata stored in string in c#	XElement.Parse("<root>"+myValue+"</root>").Value	0
5550949	5550927	Performing isnull in string	string myString = null;\nstring isNullString = myString == null ? "0" : myString;	0
10225494	10191935	Return multiple rows from database	int T = 0;\nres.rows = new List<User>();\n    int cnt = 0;\n\n    while (reader.Read())\n    {\n\n        //if (T == 0)\n        {\n            User u =new users();\n            res.rows.Add(u);\n\n            res.rows[T].age = (String)reader["age"];\n            res.rows[T].height = (String)reader["height"];\n\n            T = T + 1;\n\n        }\n        cnt = cnt + 1;               \n    }\n\n    return res;	0
8432154	8432115	Is there a way to move a file with the ability to cancel the move in the middle?	BOOL WINAPI MoveFileWithProgress(\n  __in      LPCTSTR lpExistingFileName,\n  __in_opt  LPCTSTR lpNewFileName,\n  __in_opt  LPPROGRESS_ROUTINE lpProgressRoutine,\n  __in_opt  LPVOID lpData,\n  __in      DWORD dwFlags\n);	0
3334503	3334152	avoid duplicate values in datatable	var s = (from p in dv\n             orderby p.YourColumn\n             select p.YourColumn.ToUpper()).Distinct();	0
25745986	25745853	Bringing up pictures from a database as I search for the name	SqlCommand execute = new SqlCommand('SELECT Pernr from View_PhoneBook where DisplayName= @text', conn);\n\nexecute.Parameters.Add("text", SqlDbType.Text).Value = Textbox1.text;	0
27620721	27620112	Linq and Entity Framework: Find first X datarows with same status	var nextTwo = yourTable.Take(2).ToArray() ;\nvar res = \n    nextTwo[0].status == nextTwo[1].status ? \n        nextTwo.Take(2) :\n        nextTwo.Take(1);	0
7090080	7090022	Better syntax for a return statement in a method wich retrive a query String	protected int GetPageIndex()\n    {\n        int output = 0;\n        Int32.TryParse(Request.QueryString["page"], out output);\n        return output;\n    }	0
6935056	6934861	for-in-loop/ Condition Is only used for the first element of the a List	if (GlobalClass.BlocksPositions.All(x => !DoesIntersect(Position, x))\n     Position.X += speed;	0
30826992	30826987	How to get list of specific child instances from list of parent instances?	List<LineElement> Lines = Elements.OfType<LineElement>.ToList();	0
11187271	11185147	Optimizing a formula to create a triangle from arbitrary points	# Three points are a counter-clockwise turn if ccw > 0, clockwise if\n# ccw < 0, and collinear if ccw = 0 because ccw is a determinant that\n# gives the signed area of the triangle formed by p1, p2 and p3.\nfunction ccw(p1, p2, p3):\n    return (p2.x - p1.x)*(p3.y - p1.y) - (p2.y - p1.y)*(p3.x - p1.x)	0
913407	912443	How to get a part from the full path in C#?	string strFullPath = @"C:\Users\Ronny\Desktop\Sources\Danny\kawas\trunk\csharp\ImportME\XukMe\bin\Debug\DannyGoXuk.DTDs.xhtml-math-svg-flat.dtd";\nstring strDirName; \nint intLocation, intLength;\n\nintLength = strFullPath.Length;\nintLocation = strFullPath.IndexOf("DTDs");\n\nstrDirName = strFullPath.Substring(0, intLocation); \n\ntextBox2.Text = strDirName;	0
22372861	22372827	Initialize List<> with some count of elements	var myList = Enumerable.Repeat(false, 100).ToList();	0
4175774	4175716	convert Decimal array to Double array	double[] doubleArray = Array.ConvertAll(decimalArray, x => (double)x);	0
16324967	16324913	How to get current date in DDMMYY format and split them into DD, MM and YY using C#?	DateTime today = DateTime.Now;\nint year = today.Year;\nint month = today.Month\nint day = today.Day;	0
13527257	13527221	How can I create a LINQ-friendly 'return false' expression using C# expression trees?	Expression<Func<T, bool>> falsePredicate = x => false;	0
10275750	10274553	sending an email with a previous page as the content in asp.net c# environment	Page tempPage = new Views.Blog.BlogDetail();\ntempPage.PageIntro = intro;\ntempPage.PageContent = content;\n\nStringWriter sw = new StringWriter();\nHttpContext.Current.Server.Execute(tempPage, sw, false);\nif (!String.IsNullOrEmpty(sw.ToString()))\n{\n    return sw.ToString();\n}	0
11053365	11036085	How to use Database Migrations and EF 4.3 with a code first approach to create relationship tables?	public class MyTesterContext : DbContext\n{\n    public MyTesterContext () : base("name=MyTesterContext ")\n    {\n    }\n\n    public DbSet<Trip> Trips { get; set; }\n    public DbSet<Location> Locations { get; set; }\n\n    protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Trip>().\n          HasMany(t => t.Itinerary).\n          WithMany(l => l.Trips).\n          Map(\n           m =>\n           {\n               m.MapLeftKey("TripID");\n               m.MapRightKey("LocationID");\n               m.ToTable("TripLocations");\n           });\n    }\n\n}	0
34291612	34291475	Using a timer to stop another timer	DispatcherTimer tgtTimer = new DispatcherTimer();\n        DispatcherTimer txbTimer2 = new DispatcherTimer();\n        DispatcherTimer rt = new DispatcherTimer();\n\n\npublic void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)\n    {            \n        tgtTimer.Tick += new EventHandler(tgtTimer_tick);\n        tgtTimer.Interval = new TimeSpan(0, 0, 3);\n        tgtTimer.Start();\n\n\n\n        txbTimer2.Tick += new EventHandler(txbTimer2_tick);\n        txbTimer2.Interval = new TimeSpan(0, 0, 0, 4, 000);\n        txbTimer2.Start();\n\n\n        rt.Tick += new EventHandler(rt_tick);\n        rt.Interval = new TimeSpan(0, 0, 1);\n        rt.Start();\n    }	0
2121464	2121441	How to save file in SQL Server database if have file path?	FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read);\nBinaryReader br = new BinaryReader(fs);\nint numBytes = new FileInfo(fileName).Length;\nbyte[] buff = br.ReadBytes(numBytes);	0
7475861	7475533	Using Linq to Entities to poulate comboBoxes in a winforms application, one comboBox dependent on the other	private void Form1_Load(object sender, EventArgs e)\n{\n    comboBoxAdminVisit.DataSource = be.Events;\n    comboBoxAdminVisit.DisplayMember = "EventName";\n}\n\nprivate void comboBoxAdminVisit_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (comboBoxAdminVisit.SelectedItem != null)\n    {\n        Event selectedEvent = (Event)comboBoxAdminVisit.SelectedItem;\n\n        var visitors = (from cc in be.Visitors\n                        where cc.Attending.Events.Contains(x => x.EnventId = selectedEvent.Id)\n                        select cc);\n\n        comboBoxAdminName.DataSource = visitors;\n        comboBoxAdminName.DisplayMember = "Name";\n    }\n}	0
18787510	18787411	Get the color at an offset in a Rectange with a linear gradient	RedColorYouWant = Offset * 0D + (1 - Offset) * 6F\nGreenColorYouWant = Offset * 00 + (1 - Offset) * FD\nBlueColorYouWant = Offset * F9 + (1 - Offset) * FD	0
15999512	15999308	How to start mysql database when program starts?	net start	0
9523297	9518597	How to add a checkedit control to a gridview in devexpress programmatically	DataTable dt = new DataTable();\n        dt.Columns.Add("FirstName");\n        dt.Columns.Add("Age");\n\n        dt.Rows.Add("rambo", 60);\n        dt.Rows.Add("Arnie", 35);\n        bindingSource1.DataSource = dt;\n        gridControl1.DataSource = bindingSource1;\n        gridView1.RefreshData();\n\n        gridView1.Columns.Add(\n            new DevExpress.XtraGrid.Columns.GridColumn()\n            {\n                Caption = "Selected",\n                ColumnEdit = new RepositoryItemCheckEdit() { },\n                VisibleIndex = 0,\n                UnboundType = DevExpress.Data.UnboundColumnType.Boolean\n            }\n            );	0
17027002	17001857	DirectoryNotFoundException when creating a BitmapImage	var app = Application.Current;	0
3838846	3838682	(Re)using generic parameters of a constraining type without declaring them	public class FooWrapper<T1, T2>\n  {\n     public Foo<Bar<T1, T2>> FooObj;\n\n     public FooWrapper()\n     {\n        FooObj = new Foo<Bar<T1, T2>>();\n     }\n\n     public class Foo<T> : IFoo<T1, T2> where T : Bar<T1, T2>\n     {\n        // ...\n        public void Baz() \n        {\n           Type t1 = typeof(T1);\n           Type t2 = typeof(T2);\n        }\n     }\n  }	0
23759077	23756557	How to set value in application state and use any where in project in wpf application	return (T)_values[value];	0
20745242	20744612	Generic unboxing of Expression<Func<T, object>> to Expression<Func<T, TResult>>	Expression<Func<T,object>> original = // ... something\nExpression<Func<T,TResult>> converted = Expression.Lambda<Func<T,TResult>>(\n        Expression.Convert(original.Body,typeof(TResult)), \n        original.Parameters);	0
14595407	14595341	Easy way to generate XOR checksum on a stream?	var checksum = memStream\n    .GetBuffer() // Get the underlying byte array\n    .Skip(1)     // Skip the first byte\n    .Take(memStream.Length-3) // One for the beginning, two more for the end\n    .Aggregate(0, (p,v) => p ^ v); // XOR the accumulated value and the next byte	0
908214	908119	C# TextWriter inserting line break every 1024 characters	static void Main(string[] args)\n    {\n        using (TextWriter streamWriter = new StreamWriter("lineLimit.txt")) {\n            String s=String.Empty;\n            for(int i=0;i<1025;i++){\n                s+= i.ToString().Substring(0,1);\n            }\n            streamWriter.Write(s);\n            streamWriter.Close();\n        }\n        using (TextReader streamReader = new StreamReader("lineLimit.txt"))\n        {\n            String s = streamReader.ReadToEnd();\n            streamReader.Close();\n            Console.Out.Write(s.Length);\n        }\n    }	0
1873638	1873576	Saving Bitmap Images in WPF via C#	public byte[] GetJPGFromImageControl(BitmapImage imageC)\n{\n    MemoryStream memStream = new MemoryStream();\n    JpegBitmapEncoder encoder = new JpegBitmapEncoder();\n    encoder.Frames.Add(BitmapFrame.Create(imageC));\n    encoder.Save(memStream);\n    return memStream.GetBuffer();\n}	0
6214618	6214339	Use variable as entity table name	IQueryable<T>	0
22344998	22344879	Storing user permissions in a table	ID       userID     permissionID\n------   -------    -------------\n1        4711       15\n2        4711       23\n3        4743       15\n4        4711       36	0
20316668	20316529	Increment a counter while iterating through a foreach loop	private int[] xLoc = {0,70,140,210,280,350,420};\n   private int k = 0;\n\n private void panel1_Click(object sender, EventArgs e)\n    {\n\n        int yLoc = 50;\n        foreach (MusKey mk in this.panel2.Controls)\n        {\n            if (sender == mk)\n            {\n\n                textBox1.Text = "Key No. " + mk.musicNote.ToString() + " pressed";\n                MusicNote musNote = new MusicNote(mk.musicNote,"Crotchet.bmp");\n                musNote.PlaySound();\n                this.panel3.Controls.Add(musNote);\n                musNote.ShowNote("", xLoc[k], yLoc); \n                k=k>=xLoc.Length-1? xLoc.Length:k++; // so that k does not point to non existent location\n                textBox2.Text = Convert.ToString(k); //Done for testing.. too see if k      is incrementing....\n                musNote.BringToFront();\n            } \n        } \n    }	0
27271748	27267176	Changing DataGridView Header Text At Runtime	dataGridView1.Columns["Old Column Name"].HeaderText = "New Grid Column Name";\n\n                                  or\n\n dataGridView1.Columns[column_index].HeaderText = "New Grid Column Name";	0
7378369	7377623	How to create custom controls containing populated lists?	protected override void OnCreateControl()\n  {\n     base.OnCreateControl();\n     if (Items.Count == 0)\n     {\n        Items.Add("Product 1");\n        Items.Add("Product 2");\n     }\n  }	0
30962350	30962183	Calling Web API 2 with Get is OK but fails with Post	public class WebServiceController : ApiController\n{\n    [HttpGet]\n    [Route("api/WebService")]\n    public IHttpActionResult Post(MyRequest request)\n    { \n        //work\n        return StatusCode(HttpStatusCode.OK);\n    }\n}\n\npublic class MyRequest\n{\n    public string FirstName { get; set; }\n    public string Surname { get; set; }\n}	0
21077779	21077709	How to save data from form in a specific drive	string path = System.IO.Path.Combine(@"F:\", textBox1.Text + ".txt");\n  System.IO.File.WriteAllLines(path, contents);	0
29954869	29954827	Return combined expression	public Func<double> ReturnExpression(Func<double> a, Func<double> b)\n        {\n            return () => a() * b();\n        }	0
4638986	4638979	getting a specific string fields from a Generic List to an array	listof.Select(c => c.surename).ToArray();	0
21324858	21324742	Object is String[] in c#	String[] test = { "1", "2" };\nobject o = test;\n\nif (o is string[])\n{\n   Console.WriteLine("this is string array");\n}	0
6683565	6683497	WPF How to change image visibility from another Window	partial class Window2 : Window\n{\n    ...\n    private Window1 _otherWindow;\n    private void OnClick(object sender, RoutedEventArgs e)\n    {\n        _otherWindow.image.Visibility = Visibility.Collapsed;\n    }\n}	0
29825360	29825162	How to map to "this" with AutoMapper in constructor	public MyDestinationType(MySourceType source)\n{\n    Mapper.Map<MySourceType, MyDestinationType>(source, this);\n}	0
25939939	25939013	Program cannot read xlsx file until it has been saved by Excel	string fileSpec = @"C:\Temp\TestData-Original.xlsx";\n\n    var wb = new XLWorkbook(fileSpec);\n    var ws = wb.Worksheet("Sheet1");\n\n    MessageBox.Show(ws.RowCount().ToString());	0
20711652	20711300	Controlling execution order of unit tests in Visual Studio	[TestMethod]\npublic void MyIntegratonTestLikeUnitTest()\n{\n    AssertScenarioA();\n\n    AssertScenarioB();\n\n    ....\n}\n\nprivate void AssertScenarioA()\n{\n     // Assert\n}\n\nprivate void AssertScenarioB()\n{\n     // Assert\n}	0
26441767	24144760	How to Marshal C pointer to C# array of struct	[DllImport("gatewayapi.dll", CharSet = CharSet.Ansi)]\n    static extern IntPtr AMTgetLocks(string password);\n    public RECORD[] GetLocks(string password)\n    {\n        var channels = new RECORD[MAXCHANS + 1];\n        try\n        {\n            var c = AMTgetLocks(password);\n            var crSize = Marshal.SizeOf(typeof(RECORD));\n            for (int i = 0; i < MAXCHANS + 1; i++)\n            {\n                channels[i] = (CHANNELRECORD)Marshal.PtrToStructure(c, typeof(RECORD));\n                c = new IntPtr(c.ToInt64() + crSize);\n            }\n        }\n        catch (Exception)\n        {\n            throw new Exception();\n        }\n        if (channels.Length == 0)\n        {\n            throw new Exception();\n        }\n        return channels;\n    }	0
886997	886977	How to increase the access modifier of a property	public class ChildOne : Parent\n{\n    public new int PropertyOne  // No Compiler Error\n    {\n        get { return base.PropertyOne; }\n        set { base.PropertyOne = value; }\n    }\n    // PropertyTwo is not available to users of ChildOne\n}\n\npublic class ChildTwo : Parent\n{\n    // PropertyOne is not available to users of ChildTwo\n    public new int PropertyTwo\n    {\n        get { return base.PropertyTwo; }\n        set { base.PropertyTwo = value; }\n    }\n}	0
13016336	13013345	How to pass binary image to image handler to display it in DataList?	myImageImage.ImageUrl = "data:image/jpeg;base64," + Convert.ToBase64String(myImage.Jpeg);	0
29951918	29925688	Updating a junction table with data that is present in the other tables	Db.Templates.Add(newItem);\nforeach (var record in variable.Where(record => record.Name == newItem.Name))\n    {\n         record.Templates.Add(newItem);\n    }\n\n}\nDb.SaveChanges();	0
2048832	2048790	Getter property is run without anyone calling it	DateTime.Now	0
10327789	10320232	How To Accept a File POST - ASP.Net MVC 4 WebAPI	public Task<HttpResponseMessage> PostFile() \n{ \n    HttpRequestMessage request = this.Request; \n    if (!request.Content.IsMimeMultipartContent()) \n    { \n        throw new HttpResponseException(HttpStatusCode.UnsupportedMediaType); \n    } \n\n    string root = System.Web.HttpContext.Current.Server.MapPath("~/App_Data/uploads"); \n    var provider = new MultipartFormDataStreamProvider(root); \n\n    var task = request.Content.ReadAsMultipartAsync(provider). \n        ContinueWith<HttpResponseMessage>(o => \n    { \n\n        string file1 = provider.BodyPartFileNames.First().Value;\n        // this is the file name on the server where the file was saved \n\n        return new HttpResponseMessage() \n        { \n            Content = new StringContent("File uploaded.") \n        }; \n    } \n    ); \n    return task; \n}	0
12185692	12185595	How to bring the data from the database without the HTML tags?	// I use this static method to make it faster.\nprivate static Regex oClearHtmlScript = new Regex(@"<(.|\n)*?>", RegexOptions.Compiled);\n\npublic static string RemoveAllHTMLTags(string sHtml)\n{\n    if (string.IsNullOrEmpty(sHtml))\n         return string.Empty;\n\n    return oClearHtmlScript.Replace(sHtml, string.Empty);\n}	0
1964400	1964042	How to deal with ISO-2022-JP ( and other character sets ) in a Twitter update?	using System;\nusing System.Text;\n\nclass Program {\n  static void Main(string[] args) {\n    string input = "??????";\n    Console.WriteLine(EncodeTwit(input));\n    Console.ReadLine();\n  }\n  public static string EncodeTwit(string txt) {\n    var enc = Encoding.GetEncoding("iso-2022-jp");\n    byte[] bytes = enc.GetBytes(txt);\n    char[] chars = new char[(bytes.Length * 3 + 1) / 2];\n    int len = Convert.ToBase64CharArray(bytes, 0, bytes.Length, chars, 0);\n    return "=?ISO-2022-JP?B?" + new string(chars, 0, len) + "?=";\n  }\n}	0
3807497	3807069	.NET/Security: Limiting runtime-loaded assemblies from accessing certain APIs	var myEvidence = new Evidence(new object[] {SecurityZone.Internet});\nvar newDomain = AppDomain.CreateDomain("InternetDomain");\nmyDomain.Load("MyUntrustedAssembly.dll", myEvidence);\nmyDomain.CreateInstanceAndUnwrap("MyUntrustedAssembly","MyUntrustedObjectType");\n\n//do your work with the untrusted assembly/type\n\nAppDomain.Unload(myDomain);	0
20764076	20762429	Magento API V2 Set Multiple Additional Attributes Whilst Creating Product	associativeEntity[] AdditionalAttributes = new associativeEntity[2];\n                associativeEntity isMemoAdditionalAttribute = new associativeEntity();\n                associativeEntity aaaAdditionalAttribute = new associativeEntity();\n\n      // 1st Attribute\n                    isMemoAdditionalAttribute.key = "is_memo";\n                    isMemoAdditionalAttribute.value = "1";\n                    AdditionalAttributes[0] = isMemoAdditionalAttribute;\n    // 2nd attribute\n                aaaAdditionalAttribute.key = "attrib2";\n                aaaAdditionalAttribute.value = "testvalue";\n\n                AdditionalAttributes[1] = aaaAdditionalAttribute;\n\n>    catalogProductAdditionalAttributesEntity AdditionalAttributesEntity = new catalogProductAdditionalAttributesEntity();\n                AdditionalAttributesEntity.single_data = AdditionalAttributes;// for setting single attribute\n\n\n                mageProduct.additional_attributes = AdditionalAttributesEntity;	0
8773403	8773203	How can I calculate textbox values' total with NumericUpDown?	// Get values from the text boxes\ndecimal up = Convert.ToDecimal(unitprice.Text);\ndecimal calories = Convert.ToDecimal(gizlikalori.Text);\ndecimal tot, totCalories;\n\n// Do the calculation\nif (pepper.Checked) {\n    up = up + pepperprice;\n    calories = calories + pepperkalori;\n}\ntot = up * numberofunit.Value;\ntotCalories = calories * numberofunit.Value;\n\n// Assign the results to text boxes\nunitprice.Text = up.ToString();\ntotal.Text = tot.ToString();\ngizlikalori.Text = calories.ToString();\namountofcalorie.Text = totCalories.ToString();	0
31810535	31810390	Getting all items in a list that have a property set to the same value	var grouped = SomeList.GroupBy(item => item.Bar)\n                      .OrderBy(gr=>gr.Key);\n\n\nforeach (var item in grouped)\n{\n    // item has a Key property associated with the value of Bar\n    // You can take the list of Foo by simply calling this\n    // item.ToList() and then you can process this.\n}	0
24485935	24485507	Write a generic method to replace a family of legacy API methods	public IntExp GetExpression(int value)\n{\n    return GetIntExp(value);\n}\n\npublic StringExp GetExpression(string value)\n{\n    return GetStringExp(value);\n}	0
31651324	31650506	how to fetch data from two associated tables in entity framework	var exp = from log in db.Places\n                      where log.IsActive==true\n                      select new\n                          {\n                              logId= log.Id,,\n                              experiences = from exp in log.Experiences \n                                         where(log1.LanguageId==1)\n                                         select new\n                                             {\n                                                 id=log1.Id,\n                                                 title=log1.Title\n                                             }\n                          };	0
6878216	6878161	how to display image if knows image data as binary?	public void ProcessRequest(HttpContext context)\n        {\n            Byte[] yourImage = //get your image byte array\n            context.Response.BinaryWrite(yourImage);\n            context.Request.ContentType = "image/jpeg";\n            context.Response.AddHeader("Content-Type", "image/jpeg");\n            context.Response.AddHeader("Content-Length", (yourImage).LongLength.ToString());\n            con.Close();\n\n            context.Response.End();\n            context.Response.Close();\n        }	0
11721001	11720883	How can we delete multiple file in C#?	File.Delete	0
34452401	34396002	How to get element in code behind from DataTemplate	public void TestMethod()\n{\n    DataTemplate dt = FlipView5Horizontal.ItemTemplate;\n    DependencyObject dio = dt.LoadContent();\n    foreach (var timeLine in FindVisualChildren<TextBlock>(dio)) //FindVisualTree is defined in the question :)\n    {\n        if (timeLine.Name == "xxxTB")\n        { }\n    }\n}	0
14975760	14895099	Asp.net Dynamic Data modify column size	private const int MAX_DISPLAYLENGTH_IN_LIST = 25;	0
13728091	13727994	How to insert node in TreeView as the first one?	TreeView.Nodes.Insert(0, ...)	0
3009478	3009453	C#: How to find the default value for a run-time Type?	public object GetDefaultValue(Type t)\n{\n    if (t.IsValueType) {\n        return Activator.CreateInstance(t);\n    } else {\n        return null;\n}	0
4155727	4155691	C# lambda, local variable value not taken when you think?	foreach(AClass i in AClassCollection) \n   { \n      AClass anotherI= i;\n      listOfLambdaFunctions.AddLast(  () =>  {  PrintLine(anotherI.name); }  ); \n   }	0
8007720	8007510	failed to send email from yahoo server in gmail is working	//smtp.Port = 465;\n //smtp.EnableSsl = true;	0
6693183	6692878	WPF databinding Asynchronous	Array[] array = new Array[dataGrid.SelectedItems.Count];\n\ndataGrid.SelectedItems.CopyTo(array,0);\n\nasyncUpload.BeginInvoke(array.ToList(), out tt, new AsyncCallback(test), null);	0
31187852	31187263	How do I set event methods for programmatically created combo boxes?	for (int i = 0; i < 4; i++)\n        {\n            Guid g = Guid.NewGuid();\n\n            s.Children.Add(new ComboBox()\n            {\n                Tag = g\n            });\n\n            s.Children.Add(new Label()\n            {\n                Tag = g\n            });\n        }	0
3319833	3319787	How to compare two List<String> using LINQ in C#	bool equal = collection1.SequenceEqual(collection2);	0
23856413	23785255	How to limit number of rows that can be selected in DataGridView	private void dataGridView1_SelectionChanged(object sender, EventArgs e)\n    {\n        if (dataGridView1.SelectedRows.Count > 2)\n        {\n            for (int i = 2; i < dataGridView1.SelectedRows.Count; i++)\n            {\n                dataGridView1.SelectedRows[i].Selected = false;\n\n            }\n        }\n    }	0
2808506	2808173	How to create DLL in VB.NET	YourProject/bin/Debug/YourProject.dll\nYourProject/bin/Release/YourProject.dll	0
16839516	16819591	Grab first entity from a collection in HQL (NHibernate)	manager.Employees[0]	0
24310059	24309804	Moving Controls from One Tab Page to Another	properties-events	0
4611836	4611828	Maximize application in system tray?	[STAThread]\nstatic void Main() \n{\n   using(Mutex mutex = new Mutex(false, "Global\\" + appGuid))\n   {\n      if(!mutex.WaitOne(0, false))\n      {\n         MessageBox.Show("Instance already running");\n         return;\n      }\n\n      Application.Run(new Form1());\n   }\n}	0
24342891	24341694	I am having trouble populating an array using InputBox	string value = Interaction.InputBox("Enter Array size", "Enter Array size");\nint array = 0;\nif (int.TryParse(value, out array))\n{\n    int[] size = new int[array];\n    txtOutput.Text = "Numbers: " + "\r\n";\n\n    for (int i = 0; i < size.Length; i++)\n    {\n        string prompt = Interaction.InputBox("Enter values" + (i + 1), "Enter values");\n        int num = 0;\n        if (int.TryParse(prompt, out num))\n        {\n            size[i] = num;\n            txtOutput.Text += size[i] + "\t";\n        }\n    }\n}	0
13510916	13510395	Getting value using BeginInvoke/Invoke	public void OnTagsReported()\n{\n  if (dgvScanResult.InvokeRequired)\n  {\n    dgvScanResult.Invoke(new MethodInvoker(OnTagsReported), null);\n    return;\n  }\n\n  for( var i = dgvScanResult.Rows.Count - 1; i >= 0; i-- )\n  {\n    var row = dgvScan.Rows[ i ];\n    ...\n  }  \n  ...\n}	0
17296069	17294196	How to approach production of PDF and RTF reports in a WPF application?	// get FlowDocument object\nvar uri = new Uri("/Documents/SamplePDF.xaml", UriKind.Relative);\n\nFlowDocument doc = App.LoadComponent(uri) as FlowDocument;\n\n\n// create TextRange representation of the FlowDocument\nvar content = new TextRange(doc.ContentStart, doc.ContentEnd);\n\nif (content.CanSave(DataFormats.Rtf))\n{\n    using (var stream = new FileStream(@"C:\Path\To\file.rtf", FileMode.OpenOrCreate))\n    {\n        // save it\n        content.Save(stream, DataFormats.Rtf);\n    }\n}	0
6548006	6547986	How to prevent a SQL Injection escaping strings	SqlParameter[] myparm = new SqlParameter[2];\nmyparm[0] = new SqlParameter("@User",user);\nmyparm[1] = new SqlParameter("@Pass",password);\n\nstring comando = "SELECT * FROM ANAGRAFICA WHERE E_MAIL=@User AND PASSWORD_AZIENDA=@Pass";	0
24143288	24142801	C# Regex MultiCapture	private void button1_Click(object sender, EventArgs e)\n{\n    String[] r1 = MyParser("my text 1 (Sample Text1) (9874) (1478) ");\n    String[] r2 = MyParser("Thing1 : my text 2 (Text2) (98631)");\n    String[] r3 = MyParser("This is a other Sample : mqlsdjflkj (1478) "); \n}\n\nstring[] MyParser(String Input)\n{\n    String[] RawResult;\n\n    RawResult = Input.Split(new char[] {'(', ')'},  StringSplitOptions.RemoveEmptyEntries );\n\n    List<string> Results = new List<string>();\n\n    foreach(String S in RawResult)\n    {\n        if (String.IsNullOrWhiteSpace(S) == false)\n            Results.Add(S.Trim());\n    }          \n\n    return Results.ToArray();\n}	0
27623633	27620249	How can i remove from a treeView1 only the selected child node?	if (treeView1.SelectedNode != null) {\n  if (treeView1.SelectedNode.Parent == null) {\n    treeView1.Nodes.Remove(treeView1.SelectedNode);\n  } else {\n    treeView1.SelectedNode.Parent.Nodes.Remove(treeView1.SelectedNode);\n  }\n}	0
11537907	11519725	Detect incoming call from a GSM modem in c#	private void timer1_Tick(object sender, EventArgs e)  \n    {  \n        if (port.IsOpen)  \n        {\n           string s = port.ReadExisting();\n\n               if (s.Contains("\r\nRING\r\n"))\n               {\n                   incall_status.Text = "Incoming Call....";\n                   incall_status.Visible = true;\n               }\n               else if (s.Contains("\r\nNO CARRIER\r\n"))\n               {\n                   incall_status.Text = "Call Disconnected";\n                   bgwrkr_calldisconect.RunWorkerAsync();\n               }\n\n        }\n    }	0
9456190	9456089	How to determine if a key is a letter or number?	public static bool IsKeyAChar(Keys key)\n{\n    return key >= Keys.A && key <= Keys.Z;\n}\n\npublic static bool IsKeyADigit(Keys key)\n{\n    return (key >= Keys.D0 && key <= Keys.D9) || (key >= Keys.NumPad0 && key <= Keys.NumPad9);\n}	0
10284071	10283860	Add keyboard shortcuts to console application - mono compatible	Console.CancelKeyPress	0
17324512	17324429	ASP.NET ListBox converts ListItem from text, value to text, text	lbl_users.DataSource = users;\nlbl_users.DataValueField = "userID";\nlbl_users.DataTextField = "name";\nlbl_users.DataBind();	0
28884887	28884542	how to do addition of textbox values(Integers) on Lost Focus Property and Show it in TextBlock	int sum=0;\n  private void TextBox_TextChanged(object sender, TextChangedEventArgs e)\n  {\n     sum = sum + Convert.ToInt32(_1.Text);\n     Add.Text = sum.ToString();\n  }\n  private void TextBox_TextChanged_1(object sender, TextChangedEventArgs e)\n  {\n      sum = sum + Convert.ToInt32(_2.Text);\n      Add.Text = sum.ToString();\n  }	0
31340452	31338391	How to traverse through a path and get the name of the files in a directory?	XElement root = XElement.Load("file.xml");\n\n// look for a File1\nvar file1 = root.Descendants()\n    .Where(elem => elem.Attribute("Name").Value == "File1")\n    .Single();\n\n// go 2 levels back\nvar mainFolder = file1.Parent.Parent;\n\n// display each folder\nforeach (var folder in mainFolder.Elements())\n{\n    Console.WriteLine(folder.Attribute("Name").Value);\n\n    // display each file\n    foreach (var file in folder.Elements())\n    {\n        Console.WriteLine("  " + file.Attribute("Name").Value);\n    }\n    Console.WriteLine();\n}	0
27592652	27592525	Call stored proc with DateTime parameter in Entity Framework 6	_context.Database.ExecuteSqlCommand("spGetSchedule @theDate, @teamId",\n    new SqlParameter("@theDate", DateTime.Now.Date),\n    new SqlParameter("@teamId", teamId));\n    spGetSchedule @theDate, @teamId.	0
14369477	14368651	How to implement MVP pattern for fileupload functionality	system.web	0
13724374	13724281	odd variable scope in switch statement	switch (personType)\n{\n    case 1: {\n        Employee emp = new Employee();\n        emp.ExperienceInfo();\n        break;\n    }\n    case 2: {\n        Employee emp = new Employee(); \n        // No longer an error; now 'emp' is local to this case.\n        emp.ManagementInfo();\n        break;\n    }\n    case 3: {\n        Student st = new Student();\n        st.EducationInfo();\n        break;\n    }\n    ...\n}	0
6775588	6775473	How do I make all but a certain colour black in an image?	for each pixel\n    if pixel is not green\n        pixel <- black	0
18314207	18313062	Create a Database from Script Runtime	// You can use replace windows authentication with any user credentials who has proper permissions.\nusing (SqlConnection connection = new SqlConnection(@"server=(local);database=master;Integrated Security=SSPI"))\n{\n    connection.Open();\n\n    using (SqlCommand command = connection.CreateCommand())\n    {\n        command.CommandText = "CREATE DATABASE [XYZ]";\n        command.ExecuteNonQuery();\n    }\n}\n\n// Quering the XYZ database created\nusing (SqlConnection connection = new SqlConnection(@"server=(local);database=XYZ;Integrated Security=SSPI"))\n{\n    connection.Open();\n\n    using (SqlCommand command = connection.CreateCommand())\n    {\n        command.CommandText = "select * from sys.objects";\n        ...\n    }\n}	0
3463059	3463043	LINQ to SQL - custom propery	public partial class myLinqClass {\n   public string fullFilePath {\n      get { return this.filepath + this.filename; } //clean this up as appropriate\n   }\n}	0
23736152	22816258	Payload error for windows store application	UserControl1.xaml <-- move here\n\n   UserControl2.xaml <-- move here	0
3232170	3221163	I am trying to figure out a way to streamline importing data from an access database into a .Net application	private DataSet FilterData()\n    {\n        DataSet filteredData = new DataSet("FilteredData");\n        DataView viewAccount = new DataView(global65DataSet.SET_ACCOUNT_TABLE);\n        viewAccount.Sort = "Number ASC";\n        viewAccount.RowFilter = " Number >= '" + beginningAcct+"' AND Number <= '" + endAcct + "' ";\n\n        DataView viewTrans = new DataView(global65DataSet.SET_TRANSACTION_TABLE);\n        viewTrans.Sort = "Transaction_ID ASC, DateTime ASC";\n        viewTrans.RowFilter = " DateTime >= '" + beginningDate.ToShortDateString() + "' AND DateTime <= '" +\n                              endDate.ToShortDateString() + "'";\n\n        filteredData.Tables.Add(viewAccount.ToTable());\n        filteredData.Tables.Add(viewTrans.ToTable());\n        filteredData.Tables[0].TableName = "SET_ACCOUNT_TABLE";\n        filteredData.Tables[1].TableName = "SET_TRANSACTION_TABLE";\n\n        return filteredData;\n    }	0
20554715	20554638	Selecting row if they are before a particular date	DateTime dateBase = DateTime.Parse(odDate);\nforeach (DataGridViewRow row in dataGridView1.Rows)\n{\n    DateTime dateRow = DateTime.Parse(row.Cells[0].Value.ToString());\n    row.Visible = (dateRow >= dateBase);\n}	0
11711113	11711042	Retrieving information stored in a list c# ASP.NET	for(int i =0; i <person_list.Count; i++)\n{\n  string name =  person_list[i].FirstName;\n  string email =  person_list[i].Email;\n  string daysLeft =  person_list[i].DaysLeft;\n}	0
25509565	25509288	Logging in C# console application	System.IO.Path.Combine	0
6955503	6955326	Docx file transfer from server to client using httpwebrequest/httpwebresponse	string myFileName = @"c:\temp\sample.docx";\n\n        using (WebClient wc = new WebClient())\n        {\n            wc.Proxy = null;\n            wc.DownloadFile("http://urlhere/Test.docx", myFileName);\n        }	0
7159363	7145532	How to search a treenode text similar to Outlook in c#.net ?	// Returns the node with the first hit, or null if none\n    public TreeNode Search(TreeView treeView, string text)\n    { \n        return SearchNodes(treeView.Nodes, text);\n    }\n\n    // Recursive text search depth-first.\n    private TreeNode SearchNodes(TreeNodeCollection nodes, string text)\n    {\n        foreach (TreeNode node in nodes)\n        {\n            if (node.Text.Contains(text)) return node;\n            var subSearchHit = SearchNodes(node.Nodes, text);\n            if (subSearchHit != null) return subSearchHit;\n        }\n        return null;\n    }	0
6305766	6305725	Running an exe from C# with arguments that have spaces in	myexternalexe.StartInfo.Arguments = @"comments ""\\192.168.1.1\a\here is the problem\c\d\""";	0
1170105	1169709	How do I get the characters for context-shaped input in a complex script?	[DllImport("user32.dll", CharSet=CharSet.Unicode, SetLastError=true)]\npublic static extern int DrawTextExW( HandleRef hDC\n                                     ,string lpszString\n                                     ,int nCount\n                                     ,ref RECT lpRect\n                                     ,int nFormat\n                                     ,[In, Out] DRAWTEXTPARAMS lpDTParams);\n\n[StructLayout(LayoutKind.Sequential)]\npublic struct RECT\n {\n   public int left;\n   public int top;\n   public int right;\n   public int bottom;\n }\n\n[StructLayout(LayoutKind.Sequential)]\npublic class DRAWTEXTPARAMS\n{\n  public int iTabLength;\n  public int iLeftMargin;\n  public int iRightMargin;\n  public int uiLengthDrawn;\n}	0
4022893	4022281	ASCIIEncoding In Windows Phone 7	public static byte[] StringToAscii(string s) {\n        byte[] retval = new byte[s.Length];\n        for (int ix = 0; ix < s.Length; ++ix) {\n            char ch = s[ix];\n            if (ch <= 0x7f) retval[ix] = (byte)ch;\n            else retval[ix] = (byte)'?';\n        }\n        return retval;\n    }	0
6805336	6196011	How to read XingHeaders and VBRIHeaders from MP3 files using TagLib-Sharp	foreach(ICodec codec in file.Properties.Codecs) {\n    Mpeg.AudioHeader header = (Mpeg.AudioHeader) codec;\n    if(header == null)\n        return;\n\n    if(header.XingHeader != Mpeg.XingHeader.Unknown) {\n        /* CODE HERE */\n    }\n\n    if(header.VBRIHeader != VBRIHeader.Unknown) {\n        /* CODE HERE */\n    }\n}	0
27840280	27827188	How to declare a parameter as prefix on OData	config.Routes.MapHttpRoute(\n    name: "Sample",\n    routeTemplate: "{sessionId}/{controller}"\n );\n\nconfig.MapODataServiceRoute(\n    routeName: "HSODataRoute",\n    routePrefix: "{sessionId}/",\n    model: GetEdmModel());	0
15530838	15530813	C# getting values from specific group	var l = list.Split(' ').Skip(1);	0
10898649	10898560	How to set focus to another window?	[DllImport("coredll.dll")]\n        static extern bool SetForegroundWindow (IntPtr hWnd);\n\n         private void BringToFront(Process pTemp)\n         {\n           SetForegroundWindow(pTemp.MainWindowHandle);\n         }	0
13357293	13357241	Unicode string to Chinese characters	richTextBox1.Text = reader.GetString(0)	0
19156988	19156721	attempting to return a multiple group by object	... from r in DataItems.Include(di => di.Business.Businessunit.Level1) ...	0
33380395	33366399	Adding data from dataset to datagridview table takes long time	private void Form1_Load(object sender, EventArgs e)\n{\n        DataSet DSg = ACC_Data.Get_DT(File_Path.Text.ToString());\n\n        var t = new DataTable(); \n        for (int c = 0; c < DSg.Tables[0].Columns.Count; c++) t.Columns.Add();\n\n        for (int r = 0; r < DSg.Tables[0].Rows.Count; r++)\n        {\n            string[] Dr = new string[DSg.Tables[0].Columns.Count];\n            int i = 0;\n\n            foreach (DataColumn C in DSg.Tables[0].Columns)\n            {\n               Dr[i] = DSg.Tables[0].Rows[r][C].ToString();\n               i++;\n            }\n\n            var row = t.Rows.Add(Dr);\n        }\n\n        dataGridView1.DataSource = t;\n\n}	0
32483927	32479108	Define Where Response.Redirect Should Go To Depending On Session For A Checkboxlist	protected void Step03SubmitButton_Click(object sender, EventArgs e)\n{\n  List<string> selections = Session["Step02Services"] as List<string>;\n\n  if (selections != null) {\n    if (selections.Contains("Site content uploading") || selections.Contains("Site content & layout checking")) {\n      Response.Redirect("/YourConfirmationPage.aspx");\n    } else {\n      Response.Redirect("/Step04.aspx");\n    }\n  }\n}	0
24860022	24859919	comparing two data on aspx memo with the data it contains a ";"	var aspxmemo1 = "php;visual basic;c#";\n\nvar aspxmemo2 = "visual basic;javascript";\n\nvar collection1 = aspxmemo1.Split(';');\nvar collection2 = aspxmemo2.Split(';');\n\nif (collection1.Intersect(collection2).Any())\n{\n      //Do Something\n}\n\n//Or iterate over the duplicate memo's (you get the point)\n foreach(var item in collection1.Intersect(collection2))\n {\n       Console.WriteLine(item + " occured in both collections!");\n }	0
1779229	1779175	Can this implementation of an IEqualityComparer be improved?	public class NameComparer : IEqualityComparer<FileInfo>\n{\n   public bool Equals(FileInfo x, FileInfo y)\n   {\n      if (x == y)\n      {\n         return true;\n      }\n\n      if (x == null || y == null)\n      {\n         return false;\n      }\n\n      return string.Equals(x.Name, y.Name, StringComparison.OrdinalIgnoreCase);\n   }\n\n   public int GetHashCode (FileInfo obj)\n   {\n      return obj.Name.GetHashCode ();\n   }\n}	0
30675715	30675564	In Entity Framework, how do I add a generic entity to its corresponding DbSet without a switch statement that enumerates all the possible DbSets?	public class GenericRepository<T> : where T : class\n {\n    internal YourConext context;\n    internal DbSet<T> dbSet;\n\n    public GenericRepository(YourContext context)\n    {\n        this.context = context;\n        this.dbSet = context.Set<T>();\n    }\n\n    public virtual void Insert(T entity)\n    {\n        dbSet.Add(entity);\n        context.SaveChanges();\n    }\n\n  }	0
9203979	9203761	Remove duplicate items from a List<String[]> in C#	var one = new[] {"One", "Two"};\nvar two = new[] {"One", "Two"};\nvar three = new[] {"One", "Three"};\n\nList<string[]> list = new List<string[]>(){one, two, three};\n\n\nvar i = list.Select(l => new {Key = String.Join("|", l), Values = l})\n    .GroupBy(l => l.Key)\n    .Select(l => l.First().Values)\n    .ToArray();	0
3290666	3289948	Implementing IPropertyAccessor NHibernate	public class TestEntity : Entity\n{\n    public virtual uint Unsigned { get; set; }\n    public virtual ushort UnsignedShort { get; set; }\n}\n\npublic class TestEntityMap : ClassMap<TestEntity>\n{\n    public TestEntityMap()\n    {\n        Map( x => x.Unsigned ).CustomSqlType( "bigint" );\n        Map( x => x.UnsignedShort ).CustomSqlType( "int" );\n    }\n}	0
6412917	6412874	Link button control using asp.net	var linkButton = ContentPlaceHolder1.FindControl("contentPageButton1") as LinkButton;\nlinkButton.Text = "Foo";	0
18731555	18565726	How to send data from Arduino Xbee and receive it from C#	mySerial.println(temperature);	0
16359986	16359954	Set condition in while loop	while (PeulaRashit())\n{\n    //your code\n}	0
32274729	32274427	How can I read and replace Strings line by line in a Text File?	using (StreamReader sr = new StreamReader("C:\\Users\\Donavon\\Desktop\\old.sql"))\n        {\n            int i =0;\n            string text = "";\n            do\n            {\n                i++;\n                string line = sr.ReadLine();\n                if (line != "")\n                {\n                    line = line.Replace("('',", "('" + i + "',");\n                    text = text + line + Environment.NewLine;\n                }\n\n            } while (sr.EndOfStream == false);\n        }\n        File.WriteAllText("C:\\Users\\Donavon\\Desktop\\new.sql", text);	0
15280660	15279281	How to refresh DataGrid?	System.Collections.IEnumerable temp = yourGrid.ItemsSource;\n yourGrid.ItemsSource = null;\n yourGrid.ItemsSource = temp;	0
24633550	24633326	Can I send a string (or a specific number) on connecting an Async socket	Connect()	0
7472600	7472393	Winforms Checkbox combobox single click instead of double click	/// <summary>\n/// Processes Windows messages.\n/// </summary>\n/// <param name="m">The Windows <see cref="T:System.Windows.Forms.Message" /> to process.</param>\n[SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)]\nprotected override void WndProc(ref Message m) {\n    if (m.Msg == (NativeMethods.WM_COMMAND + NativeMethods.WM_REFLECT) && NativeMethods.HIWORD(m.WParam) == NativeMethods.CBN_DROPDOWN) {\n        // Wout: changed this to use BeginInvoke instead of calling ShowDropDown directly.\n        // When calling directly, the Control doesn't receive focus.\n        BeginInvoke(new MethodInvoker(ShowDropDown));\n        return;\n    }\n    base.WndProc(ref m);\n}	0
14268075	14268048	How to return a string[] containing values of an Enum	string[] names = Enum.GetNames(typeof(Fruits));	0
29552030	29551498	How to make one type list of tupel items?	// List<Tuple<int, double>>\nvar list1 = multiValueList.Select(t=>Tuple.Create(t.Item1, t.Item2)).ToList();\n\n// List<string>\nvar list2 = multiValueList.Select(t=>t.Item3).ToList();	0
7887405	7886860	How find datarows and change index of datarow in an existing datatable?	private void ModifyTable(DataTable toModify)\n    { //Add a column to sort by later. \n        DataColumn col = toModify.Columns.Add("DummySort", typeof(int));\n        col.DefaultValue = 0;\n    }\n    private void SetDummyColumnValue(DataRow dr, int value)\n    { //Mark the columns you want to sort to bring to the top. \n        //Give values bigger than 0! \n        dr["DummySort"] = value;\n    }\n    private DataTable GetSortedTable(DataTable modifiedTable)\n    {\n        //Sort by the column from bigger to smaller \n        DataView dv = new DataView(modifiedTable);\n        dv.Sort = "DummySort DESC"; return dv.ToTable();\n    }	0
23602147	23601881	Remove the Labels after draw them dynamically	private void RemoveOldLabels()\n  {\n    List<Label> LabelsToRemove = new List<Label>();\n\n    foreach (var x in this.picNodes.Controls)\n    {\n        if (x.GetType() == typeof(System.Windows.Forms.Label))\n        {\n            LabelsToRemove.Add((Label)x);\n        }\n    }\n\n    foreach (var label in LabelsToRemove)\n    {\n        this.picNodes.Controls.Remove(label);\n        label.Dispose();\n    }\n  }	0
12244512	12243709	Process Multiple XML Files from Folder	XmlDocument xDoc = new XmlDocument();\n        string path = Directory.GetCurrentDirectory();\n        foreach (string file in Directory.EnumerateFiles(path, "*.xml"))\n        {\n          xDoc.Load(System.IO.Path.Combine(System.IO.Directory.GetCurrentDirectory(), file));\n          string strpath = xDoc.BaseURI;\n        }	0
22902236	22901986	Items Template code-behind	public partial class MainPage : PhoneApplicationPage\n{\n    // Constructor\n    public MainPage()\n    {\n        InitializeComponent();\n\n        People.Loaded += People_Loaded;\n    }\n\n    void People_Loaded(object sender, System.Windows.RoutedEventArgs e)\n    {\n        for (int i = 0; i < People.Items.Count; i++)\n        {\n            var container = People.ItemContainerGenerator.ContainerFromIndex(i);\n            container.SetValue(SlideInEffect.LineIndexProperty, i);\n        }\n    }\n}	0
11889845	11876302	Drawing image to canvas in metro app	StorageFile file;\nStorageFolder InstallationFolder = Windows.ApplicationModel.Package.Current.InstalledLocation;      \n\nstring filePath = @"Assets\dock.jpg";\nfile = await InstallationFolder.GetFileAsync(filePath);\nIRandomAccessStream dockpic = await file.OpenAsync(0);\nBitmapImage dockimage = new BitmapImage();\ndockimage.SetSource(dockpic);\n\nRectangle blueRectangle = new Rectangle();\nblueRectangle.Height = 100;\nblueRectangle.Width = 200;\n// Create an ImageBrush\nImageBrush imgBrush = new ImageBrush();\nimgBrush.ImageSource = dockimage;\n\n// Fill rectangle with an ImageBrush\nblueRectangle.Fill = imgBrush;\npaintCanvas.Children.Add(blueRectangle);	0
7545286	7545215	How to send a table-type in parameter to T-SQL while using C# IDataReader?	var dt = new DataTable();\n... set up dt ...\npar = new SqlParameter("@TemplatesIds", SqlDbType.Structured, dt)	0
30918371	30918299	Find string in enum	var integers = Enum.GetValues(typeof(Status))\n                   .Cast<Status>()\n                   .Where(status => status.ToString().Contains("InStock"))\n                   .Select(status => (int) status);	0
4582878	4582863	Execute a function from a variable in C#	switch (variable) {\n  case "OneMethod": OneMethod(); break;\n  case "OtherMethod": OtherMethod(); break;\n}	0
378363	378217	Cannot Detach from process using mdbg	MgProcess.CorProcess.Stop(0);\n  MgProcess.Detach();	0
24278450	24277764	To find the number of rows in DataGridView where the values are between specified range?	var values = gvtest.Rows.Cast<GridViewRow>().Select(x => x.Cells[0].Text);\nvar sector1 = values.Count(x => Convert.ToInt32(x) >= 0 && Convert.ToInt32(x) < 30);	0
425332	425325	Using C#, how can I set a Url property to an HTML file in my project?	public void LoadPageFromDisk(string filePath)\n{\n    Uri targetPage = null;\n\n    string workingPageURI = filePath.Trim();\n\n    workingPageURI = Path.GetFullPath(workingPageURI);\n\n    if (Uri.TryCreate(workingPageURI, UriKind.RelativeOrAbsolute, out targetPage) == true)\n    {\n\n        webBrowserControl.Navigate(targetPage);\n    }\n\n}	0
32317937	32317883	Interfaces exposing generic overload. How to DRY here?	public static MyInterfaceExtensions\n{\n    public T Create<T>(this IMyInterface target)  \n    {\n        return (T) target.Create(typeof(T)); \n    }\n}	0
25155582	25155482	Proper Linq Query for objects with many to many relation ship generated with code first entity framework	var productCategory = await db.ProductCategories.Include(p => p.Categories.Select(c => c.Products)).FirstOrDefaultAsync(category => category.Id == Id);	0
19059829	19059762	Comparing contents of string array elements with names	private static int FindStudentPosition(string name, string[] array)\n{\n    int intLocation = -1;\n    //loops through all array elements\n    for (int i = 0; i < array.Length; i++; )\n    {\n        //checks if array element matches name\n        if (array[i] == name)\n        {\n            //displays message and stores position in intLocation\n            Console.WriteLine("Matches Name " + i);\n            intLocation = i;\n            break; // break when match found\n        }    \n    }\n    return intLocation;\n}	0
156365	156113	LinqToSql and abstract base classes	static Expression<Func<T, bool>> BuildWhere<T>(int deviceId) {\n    var id = Expression.Constant(deviceId, typeof(int));\n    var arg = Expression.Parameter(typeof(T), "x");\n    var prop = Expression.Property(arg, "DeviceId");\n    return Expression.Lambda<Func<T, bool>>(\n        Expression.Equal(prop, id), arg);\n}	0
14554487	14553954	Remove strange hidden charecters from my JSON before deserializing	([\S\s]*\"])\"UDF5\" : \"[\S\s]*?\",([\S\s]*)	0
8521715	8521253	Disable Button after Click whilst maintaining CausesValidation and an OnClick-Method	protected override void OnLoad(EventArgs e)\n{\n    base.OnLoad(e);\n   // prevents form from being submitted multiple times in MOST cases\n   // programatic client-side calls to __doPostBack() can bypass this\n    Page.ClientScript.RegisterOnSubmitStatement(GetType(), "ServerForm",\n    "if (this.submitted) return false; this.submitted = true; return true;");\n}	0
4107760	4107685	Add space after each fourth + sign	string input = "A01+B02+C03+D04+E05+F06+G07+H08+I09+J10+K11+L12+M13+N14+O15+P16";\n\nstring final = string.Join(\n    "+", \n    input\n        .Split('+')\n        .Select( (s, i) => (i>0 && i%4==0) ? " "+ s : s));	0
1473424	1473390	How to access a C# internal property from VB.NET project in same solution?	[assembly:InternalsVisibleTo("MyVbAssemblyName")]	0
9003865	9003820	How to convert Char[] or String to Char* for initialize SecureString in C#?	string s = "Hello";\nSecureString ss = new SecureString();\n\nforeach(char c in s) ss.AppendChar(c);	0
31206671	31206541	How to pass extra parameter to Tapped Event?	private void TxtName_Tapped(object sender, TappedRoutedEventArgs e)\n    {\n        clickedElementName = ((TextBlock)sender).Name ;\n        if(clickedElementName == "element1")\n        {\n        }\n    }	0
1359340	1359319	change AM to PM?	DateTime dateValue;\n  string dateString = "2/16/2008 12:15:12 PM";\n  try {\n     dateValue = DateTime.Parse(dateString);\n     Console.WriteLine("'{0}' converted to {1}.", dateString, dateValue);\n  }   \n  catch (FormatException) {\n     Console.WriteLine("Unable to convert '{0}'.", dateString);\n  }	0
17205684	17205547	Do I need to create a two-dimensional array to add reference data with an id column into Entity Framework?	List<ContentType> contentTypes = new List<ContentType>();\n\n//Fill Your List With Names and IDs\n//Eg: contentTypes.Add(new ContentType(0,"Menu")) and so on and so forth then:\n\nforeach (ContentType contentType in contentTypes )\n{\n        _uow.ContentTypes.Add(contentType);\n}	0
18104473	18104392	Adding values to member fields of object in List<T> at same index	mhpList = new List<MHP>();\n\nmhpList.Add(new MHP\n{\n MHP_Name = something,\n MHP_AC = a number\n});\n\nmhpList[0].MHP_ParId= "Something";	0
4328682	4328641	C# Enum using values in Sql Server table	Dictionary<int, string>	0
4402234	4402008	InvalidCastException implementing .net events in native c++ with managed wrapper	public delegate void ReportProgressDelegate(Double ^completionPercentage);	0
19757440	19756860	Executing an external program via c# without showing the console	process.StartInfo.Arguments = "-I dummy --dummy-quiet";	0
17006538	17006496	C# Data Annotations in Interface	Interface IFoo\n{\n   [Required]\n   string Bar {get; set;}\n}\n\nInterface IBar\n{\n   string Bar {get; set;}\n}\n\nClass Foo : IFoo, IBar\n{\n   string Bar {get; set;}\n}	0
2058674	2058616	Linq to SQL: Using int? as a parameter in a query	public IQueryable<Clam> getAllClams(int clamTypeID, int? parentClamID)\n{\n     return from clam in Clams\n            where clam.ClamTypeID == clamTypeID &&\n                  object.Equals(clam.ParentClamID, parentClamID)\n            select clam;\n}	0
33326980	33326848	C# - How update a web page after an async method call?	public static async string Save(...)\n{\n    //Get all active controllers\n    List<Controller> lstControllers = Controller.Get();\n\n    //Create a task object for each async task\n    List<Task<returnValueType>> controllerTasks = lstControllers.Select(controller=>{\n        DeviceControllerAsync caller = new DeviceControllerAsync(ArubaBL.RegisterDevice);\n        return Task.Factory.FromAsync<returnValueType>(caller.BeginInvoke, caller.EndInvoke, null);\n    }).ToList();\n\n    // wait for tasks to complete (asynchronously using await)\n    await Task.WhenAll(controllerTasks);\n\n    //Do something with the result value from the tasks within controllerTasks\n}	0
22858386	22857734	How to handle multiple input combinations in a convenient way in C#	int i = booleans[0]?1:0 \n      + 2*(booleans[1]?1:0)\n      + 4*(booleans[2]?1:0)\n      + 8*(booleans[3]?1:0);\n\nswitch (i)\n{\n   case 0: //false false false false\n   case 1: //true false false false\n   case 2: //false true false false\n   //...\n   case 15: //true true true true\n}	0
26973072	26972066	Type from IntPtr handle	private static Type GetTypeFromHandle(IntPtr handle)\n{\n    var method = typeof(Type).GetMethod("GetTypeFromHandleUnsafe", BindingFlags.Static | BindingFlags.NonPublic);\n    return (Type)method.Invoke(null, new object[] { handle });\n}\n\nprivate static void Main(string[] args)\n{\n    IntPtr handle = typeof(string).TypeHandle.Value;//Obtain handle somehow\n\n    Type type = GetTypeFromHandle(handle);\n}	0
4601200	4601144	Sum Of a column of generic list	var lst = new List<int>();\nlst.Sum();	0
6567998	6567483	how to call dll file without using statment in c#	object calcInstance = Activator.CreateInstance(calcType);\nor    \nAssembly testAssembly = Assembly.LoadFile(@"c:\Test.dll");	0
11694448	11694193	I have a textfile and I want to replace a string in it with empty string but	using System;\nusing System.Text.RegularExpressions;\n\nclass Program\n{\n  static void Main()\n  {\n    string input = "select ceiling(a.interest) as interest, a.myID as mID, a.studentID as sID from mytable";\n    string column = "a.myID";\n    string pattern = "((?<=\\bselect)\\s+[^,]*\\b" + Regex.Escape(column) + "\\b[^,]*\\s*,?|\\s*,\\s*[^,]*\\b" + Regex.Escape(column) + "\\b[^,]*(?=(?:,|\\sfrom\\b)))";\n    string output = Regex.Replace(input, pattern, "", RegexOptions.IgnoreCase);\n    Console.WriteLine(output);\n  }\n}	0
6454131	6442747	Add the default outlook signature in the email generated	private string ReadSignature()\n{\n    string appDataDir = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\Microsoft\\Signatures";\n    string signature = string.Empty;\n    DirectoryInfo diInfo = new DirectoryInfo(appDataDir);\n\n    if(diInfo.Exists)\n    {\n        FileInfo[] fiSignature = diInfo.GetFiles("*.htm");\n\n        if (fiSignature.Length > 0)\n        {\n            StreamReader sr = new StreamReader(fiSignature[0].FullName, Encoding.Default);\n            signature = sr.ReadToEnd();\n\n            if (!string.IsNullOrEmpty(signature))\n            {\n                string fileName = fiSignature[0].Name.Replace(fiSignature[0].Extension, string.Empty);\n                signature = signature.Replace(fileName + "_files/", appDataDir + "/" + fileName + "_files/");\n            }\n        }\n    }\n        return signature;\n}	0
1191855	910063	Allow only alphanumeric in textbox	private void _txtPath_KeyDown(object sender, KeyEventArgs e)\n  {\n     if ((e.Key < Key.A) || (e.Key > Key.Z))\n        e.Handled = true;\n  }	0
2687830	2675372	How to get Content types	Web.Webs WebService = new Web.Webs();\n        WebService.Credentials = new NetworkCredential("username", "password");\n        XmlNode list = WebService.GetContentTypes();	0
12242383	12242067	Conditional DataGridView to DataTable conversion	var dtableDemo = new DataTable();\ndtableDemo = this.dgvDemo.DataSource as DataTable; //// Getting the datatable of datagridview datasource\nif (dtableDemo != null)\n{\n    dtableDemo.Columns.RemoveAt(0); //// Removing the first column of derived table\n\n    dtableDemo.Rows.Cast<DataRow>().Where(\n               row => row.ItemArray.Contains("put_your_value_to_check")).ToList()\n               .ForEach(row => row.Delete()); //// Remove the row if it contains the given value\n    dtableDemo.AcceptChanges(); //// Finalize the delete\n}	0
3537488	3537415	connect custom list with control like combobox	// item type to display in the combobox\npublic class Item\n{\n    public int Id { get; set; }\n    public string Text { get; set; }\n}\n\n// build new list of Items\nvar data = List<Item>\n{\n    new Item{Id = 1, Text = "Item 1"},\n    new Item{Id = 2, Text = "Item 2"},\n    new Item{Id = 3, Text = "Item 3"}\n};\n\n// set databind\ncomboBox1.DataSource = data;\ncomboBox1.ValueMember = "Id";  // the value of a list item should correspond to the items Id property\ncomboBox1.DisplayMember = "Text";  // the displayed text of list item should correspond to the items Id property\n\n// get selected value\nprivate void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n    var selectedValue = comboBox1.SelectedValue;        \n}	0
7298718	7298670	not able to see all file type images at a time when button clicked	openFileDialog1.Filter = "png files (*.png)|*.png|jpg files (*.jpg)|*.jpg|jpeg files (*.jpeg)|*.jpeg|gif files (*.gif)|*.gif|Image Files(*.png;*.jpg;*.jpeg;*.gif)|*.png;*.jpg;*.jpeg;*.gif";	0
3475970	3468663	Creating excel document as attachment on a sharepoint list	wspart.Worksheet.Save();\ndocument.WorkbookPart.Workbook.Save();	0
32092737	32092410	Get path of image to fileupload	string Img1, unq1;\nstring filepath = "~/YourFolder/";\nimg1 = System.IO.Path.GetFileName(gridusers.SelectedRow.Cells[2].ImageName);\nunq1 = filepath + img1;	0
28657856	28656816	How can i get the url that raised the AssociationUriMapper in WP8?	/FileTypeAssociation?fileToken=17B9F681-058D-4B01-B33F-FAFF70760D25	0
10227569	10226797	Storing and retrieving checkbox selected items in WP7 Local Database using C#	// to display user selection - days is a List<DayOfWeek> as stored by you in database\nforeach(var day in days)\n{\n    ListBoxItem lbi = new ListBoxItem();\n    TextBlock tb = new TextBlock();\n    tb.Text = day.ToString();\n\n    lbi.Content = tb;\n    lbi.VerticalContentAlignment = System.Windows.VerticalAlignment.Center;\n    lbi.IsSelected = AlarmMod.AlarmData.SelectedDays.Contains(day);\n\n    this.listBox.Items.Add(lbi);\n}\n\n// to store\nList<DayOfWeek> iDays = new List<DayOfWeek>();\n\nfor (int i = 0; i < 7; i++)\n{\n    if ((this.listBox.Items[i] as ListBoxItem).IsSelected)\n    {\n        iDays.Add((DayOfWeek)i);\n    }\n}\n// now you store iDays which is a List<DayOfWeek> in database.	0
15221547	15221254	Scheduled Task using Windows Services and XML	public class ScheduleThread \n{\n    private readonly TimeSpan _timeSpan;\n    private readonly Timer _timer;\n    public bool IsRunning { get; protected set; }   \n    public ScheduleThread()\n    {\n        IsRunning = false;\n                    //set the timespan according your config            \n        _timeSpan = new TimeSpan();\n    }\n    public void Start()\n    {\n        if (IsRunning == false)\n        {\n            IsRunning = true;\n            StartTimer();\n        }\n    }\n    private void StartTimer()\n    {\n                    _timer = new Timer(CallBack);\n        _timer.Change(_timeSpan, TimeSpan.Zero);\n    }\n    public void Stop()\n    {\n        if (IsRunning)\n        {\n            _timer.Dispose();\n            IsRunning = false;\n        }\n    }\n    private void CallBack(object obj)\n    {\n        //if process is not running\n        //start process\n    }       \n}	0
25183816	25183719	C# ASP.NET - No overload for method 'Add' takes 1 arguments	public class AirportClass\n    {\n        private string connectionString;\n        private SqlConnection connection;\n        private SqlCommand command;\n        private List<string> items;\n\n        public AirportClass()\n        {\n            connectionString = @"Server=server;database=database;uid=username;pwd=password;";\n        }\n\n        public List<string> getListItems()\n        {\n            items = new List<string>();\n            connection = new SqlConnection(connectionString);\n            command = new SqlCommand("SELECT * FROM Table");\n            command.Connection = connection;\n            connection.Open();\n            SqlDataReader dataReader = command.ExecuteReader();\n            while (dataReader.Read())\n            {\n                string data = dataReader.GetValue(0).ToString();\n                items.Add(data);\n            }\n            connection.Close();\n            return items;\n        }\n    }	0
18408798	18408757	Using LINQ to select with object	testesiteEntities db = new testesiteEntities();//create object\n\n//select object\nrblCategoria.DataValueField = "codcategoria"; \nrblCategoria.DataTextField = "dsccategoria";\nrblCategoria.DataSource = db.categoria.Select().ToList();\nrblCategoria.DataBind();//define valores no bullet list	0
28214401	28214337	Split data with Tab in a table in C#	foreach (var account in sortedAccounts)\n                        {\n                            var outputLine =\n                            account.accountholder + "\t" +\n                            account.accountnumber + "\t" +\n                            account.accounttype.Substring(0, 2) + "\t" +\n                            account.amount + "\t" +\n                            account.date.ToShortDateString();\n\n                            //output\n                            File.WriteAllText(text, outputLine);\n                        }	0
869141	869122	How to Search Through a C# DropDownList Programmatically	foreach (ListItem li in dropdownlist1.Items)\n{\n    if (li.Value == textBox1.text)\n    {\n       // The value of the option matches the TextBox. Process stuff here.\n    }\n}	0
3461808	3461050	selecting a node in a treeview, on select of a node in a separate treeview	secondTree.HideSelection = false;	0
11199912	11199891	Calling a function from within another function?	namespace Different \n{\n    public class Class1\n    {      \n        public static int[] Function1()\n        {\n           // code to return value\n        }\n    }\n}\n\nnamespace MyNamespace\n{    \n    class Program\n    { \n          static void Main(string[] args)\n          {\n              // Error\n              var arr = Class1.Function();\n\n              // you need to use...\n              var arr = Different.Class1.Function();\n          }\n    }\n}	0
21217836	21217801	Regex modify connection string	string pattern = @"\bDriver=[^;]+;";\nstring replacement = "";\nRegex rgx = new Regex(pattern);\nstring result = rgx.Replace(input, replacement);	0
17753721	17753670	Create new array using content of other arrays in C#	string[] ASIA = new []{ Taiwan, Vietnam, Korea, China, Japan}\n                      .SelectMany(s => s)  // not entirely sure what these abbreviations are...\n                      .ToArray();	0
2412029	2411901	How can I loop through table rows to toggle the display style?	function vehicleSelected() {  \n        var autoSelect = document.getElementById('vehicleSelect');  \n        var strAuto = autoSelect.options[autoSelect.selectedIndex].value;                                  \n        var rows = document.getElementById('tableList').getElementsByClassName('TR');             \n        for (var i = 0; i < rows.length; i++) {    \n            rows[i].style.display='none'; // note: better to use a css class here\n        }  \n        var selectedRow = document.getElementById(strAuto); // assuming that the values are the same as the row Id's.\n        selectedRow.style.display = ''; // again, better to use a Css style.\n    }	0
4095594	4095455	Filling Windows XP Security Event Log	secpol.msc	0
14768997	14768918	C# xml inline array deserialization	List<string> items = XDocument.Parse("the xml")\n                         .Descendants("item")\n                         .Select(item => item.Attribute("id").Value).ToList();	0
2667058	2667024	Singleton Pattern for C#	public sealed class Singleton\n{\n    private static readonly Singleton instance = new Singleton();\n    static Singleton() {} // Make sure it's truly lazy\n    private Singleton() {} // Prevent instantiation outside\n\n    public static Singleton Instance { get { return instance; }\n}	0
24456894	24456632	How to define unmanaged dll dependency in C#	[DllImport(@"..\lib\DDS_Service.dll", EntryPoint="SetCallback")]\n   private static extern void SetCallback(Callback fn);	0
34436673	34436458	Unity C#, How to call a function from another script to start animation?	void Start()\n    {\n        ClickToMove = FindObjectOfType<ClickToMoveScript>();\n        ClickToMove.PlayWoodCuttingAnim();  \n    }	0
26116618	26116269	What does it mean if a person says that a particular datastructure can enumerate?	internal class Test \n{\n    public Enumerator GetEnumerator()\n    {\n        return new Enumerator();\n    }\n\n    public struct Enumerator\n    {\n        public bool MoveNext()\n        {\n            return false;\n        }\n\n        public object Current\n        {\n            get { return null; }\n        }\n    }\n}	0
24675052	24674875	Delete rows which has a specific value from DataGridView C#	for(int v = 0; v < dataGrid1.Rows.Count; v++)\n{\n    if(string.Equals(dataGrid1[0, v].Value as string, "ITM-000001"))\n    {\n        dataGrid1.Rows.RemoveAt(v);\n        v--; // this just got messy. But you see my point.\n    }\n}	0
19925311	19924701	How to fill a SQL Server database in a C# winform	-- declare input - could be the input parameter of a stored procedure or something\nDECLARE @input XML = '<Employees><Employee><ID>4040</ID><Vorname>Dieter</Vorname><Nachname>Mueller</Nachname></Employee></Employees>'\n\n-- INSERT INTO your table\nINSERT INTO dbo.Employee(ID, Vorname, Nachname)\n    -- shred the incoming XML into rows of data, based on the XPath /Employees/Employee\nSELECT\n    XEmp.value('(ID)[1]', 'int'),\n    XEmp.value('(Vorname)[1]', 'varchar(50)'),\n    XEmp.value('(Nachname)[1]', 'varchar(50)')\nFROM \n    @input.nodes('/Employees/Employee') AS XTbl(XEmp)	0
10539897	10524487	Observing a threadsafe collection using the Reactive Framework	IObservable<bool> ValidateAsync(Row item)\n{\n    return Observable.Start(() => {\n        // TODO: Figure out if the row is valid\n        return true;\n    }, Scheduler.TaskPoolScheduler);\n}\n\nmyBigDataTable.ToObservable()\n    .Select(x => ValidateAsync(x).Select(y => new { Row = x, IsValid = y }))\n    .Merge(10 /* rows concurrently */)\n    .ObserveOn(SynchronizationContext.Current /*assuming WinForms */)\n    .Subscribe(x => {\n        Console.WriteLine("Row {0} validity: {1}", x.Row, x.IsValid);\n    });	0
30875370	30875279	How to cancel a CancellationToken	// Define the cancellation token.\nCancellationTokenSource source = new CancellationTokenSource();\npreviouslyProvidedToken = source.Token;\n...\nsource.Cancel();	0
25449317	25434686	How to merge rows in a DataTable when data in multiple columns match?	DataTable dtFinal = dtOriginal.Clone();\nfor (int i = 0; i < dtOriginal.Rows.Count; i++)\n{\n    bool isDupe = false;\n    for (int j = 0; j < dtFinal.Rows.Count; j++)\n    {\n        if (dtOriginal.Rows[i][0].ToString() == dtFinal.Rows[j][0].ToString()\n            && dtOriginal.Rows[i][1].ToString() == dtFinal.Rows[j][1].ToString()\n            && dtOriginal.Rows[i][2].ToString() == dtFinal.Rows[j][2].ToString())\n        {\n            dtFinal.Rows[j][3] = int.Parse(dtFinal.Rows[j][3].ToString()) + int.Parse(dtOriginal.Rows[i][3].ToString()); \n            isDupe = true;\n            break;\n        }\n    }\n\n    if (!isDupe)\n    {\n        dtFinal.ImportRow(table.Rows[i]);\n    }\n}	0
443674	443662	string split based on char \	Split('\\')	0
31700731	31694366	How to insert special character like '? ','? ' in database using c#	using (var streamReader = new StreamReader(jsonStream, Encoding.GetEncoding("iso-8859-1")))	0
18643113	18642902	How to update dropDownList on the onTextChange event of a textBox	protected void txtDate_TextChanged(object sender, EventArgs e)\n     {\n          SqlDataSource2.SelectCommand = "NEW SQL COMMAND";\n          DropDownList1.DataSourceID = "SqlDataSource2";\n     }	0
12393630	12393494	How do I configure my ASP.NET directory to allow writing a log file?	System.IO.File.WriteAllLines(Server.MapPath("~/App_Data/log.txt"))	0
2636473	2636468	DateTime in SqlServer VisualStudio C#	SqlCommand command = new SqlCommand();\ncommand.Connection = someConnectionObj;\ncommand.CommandText = "INSERT INTO Sometable (datecolumn) VALUES (@p_date)";\ncommand.Parameters.Add ("@p_date", SqlDbType.DateTime).Value = someDate;\ncommand.ExecuteNonQuery();	0
17020516	17020452	I'm getting null characters at the end of string	string s = ...;\ns = s.TrimEnd('\0');	0
25786058	25288801	Cross Thread Exception when trying to display Images from Camera Roll on Windows Phone	Device.BeginInvokeOnMainThread(() => { App.Locator.TaggingPageVM.ImageSrc = sender.Result[0].Source; });	0
19051141	19051080	How do i add more time to the datetime.now parse it then reset back to the original datetime.now?	dt = GetNetworkTime().AddDays(1);	0
22336185	22336009	Handling sounds that match strings?	string input = "CaptainNillo";\nstring first = listFO.FirstOrDefault(x => input.StartsWith(x));\nstring second = listFN.FirstOrDefault(x => input.EndsWith(x));\nif (first != null && second != null)\n   // play first.wav and second.was	0
22176310	22176160	Selecting specifie row in Asp	...\n    using (var dr = cmd.ExecuteReader())\n    {\n        while (dr.Read()) //for each item in the datatable\n        {\n            dr.GetString(0);\n        }\n    }	0
20321304	20321236	How to use properties in Inheritance with C#?	class PsudoStream \n{\n    public virtual bool CanRead { get { return false; } }\n    public virtual bool CanWrite { get { return false; } }\n}\n\nclass WritableStream : PsudoStream \n{\n    //CanRead is false already and does not need to be overwritten\n\n    public override bool CanWrite { get { return true; } }\n}\n\nclass ReadableStream : PsudoStream \n{\n    //CanWrite is false already and does not need to be overwritten\n\n    public override bool CanRead { get { return true; } }\n}	0
21883193	21846940	How can I get if checkbox is checked	if (o.NodeType == NodeType.Element && o is GeckoInputElement)\n{\n      GeckoInputElement asd = (GeckoInputElement)o;\n      if (asd.Checked)\n        ....\n}	0
10489092	10489018	Using IDbConnection	public static class IDbConnectionExtensions {\n    public static void MyExtension(this IDbConnection connection) {\n        Console.WriteLine("Hello, connection!");\n    }\n}	0
18379761	12511809	How to copy DataGrid cell value to clipboard	private void DataGrid_CopyingRowClipboardContent(object sender, DataGridRowClipboardEventArgs e)\n{\n    var currentCell = e.ClipboardRowContent[ dataGrid.CurrentCell.Column.DisplayIndex];\n    e.ClipboardRowContent.Clear();\n    e.ClipboardRowContent.Add( currentCell );\n}	0
14070526	14070275	Find duplicates, missing numbers, missing order in integer array	var dupeNumbers = new int[]{1,2,3,4,2,5};\n\nvar dupes = dupeNumbers\n    .GroupBy(n => n)\n    .Where(g => g.Count() > 1)\n    .Select(g => g.Key);\n\nvar rageNumbers = new int[]{1,2,3,5,6,7};\nvar fullRange = Enumerable.Range(rageNumbers.Min(), rageNumbers.Max());\n\nvar missing = fullRange\n    .GroupJoin(rageNumbers, n => n, full => full, (full, n) => new { full, n })\n    .SelectMany(joined => joined.n.DefaultIfEmpty(), (full, n) => new{ Full = full.full, n})\n    .Where(joined => joined.Full != joined.n)\n    .Select(n => n.Full);	0
27839690	27839547	Finding the subnet mask of your local PC	public static void GetSubnetMask()\n    {\n        foreach (NetworkInterface adapter in NetworkInterface.GetAllNetworkInterfaces())\n        {\n            foreach (UnicastIPAddressInformation unicastIPAddressInformation in adapter.GetIPProperties().UnicastAddresses)\n            {\n                if (unicastIPAddressInformation.Address.AddressFamily == AddressFamily.InterNetwork)\n                {\n                    Console.WriteLine(unicastIPAddressInformation.IPv4Mask);\n                }\n            }\n        }\n    }	0
24664797	24657307	SecurityTokenSignatureKeyNotFoundException when validating JWT signature	var credentials = new X509CertificateCredentials(\n    cert,\n    new SecurityKeyIdentifier(\n        new NamedKeySecurityKeyIdentifierClause(\n            "kid",\n            "F8A59280B3D13777CC7541B3218480984F421450")));	0
18763118	18724464	ASP Chart. Multiple X axis values	seriesSmall.YAxisType = AxisType.Secondary;	0
20275577	20275492	OOP Array filtering using a string?	foreach(Results result in _results)\n    {\n        int examID = _theDisplay.userInputAsInteger("Select a result");\n        _findExamIndex(examID, _exams);\n         int studentID = _theDisplay.userInputAsInteger("Please select a users result");\n        _findStudentIndex(studentID, _students);\n\n         //filter on the _exams' Topic == '_topicName'\n         exam[]  exams  = FindExamByTopic("youtopic",_exams)\n\n    }\n\n\n  private Exam[] FindExamByTopic(string topic, Exam[] _exams)\n    {\n         return _exams.Where(ex => ex.Topic == topic).ToArray();  \n    }\n\n\n  //here without using  linq \n\n     private Exam[] FindExamByTopicSimple(string topic, Exam[] _exams)\n    {\n        List<Exam>  exams = new List<Exam>();\n\n        for (int i = 0; i < _exams.Length; i++)\n        {\n            if (_exams[i].Topic == topic)\n            {\n                exams.Add(_exams[i]); \n            }\n        }\n        return exams.ToArray();   \n    }	0
29601735	29601582	WPF DataGrid in the child window is not getting data-bound somehow	public partial class RecComparer : Window\n{\n    public BaselineEntity _blEnty{get;set}\n    public List<RecComparisionData> _compData {get;set}\n\n    public RecComparer(BaselineEntity blEnty)\n    {\n        InitializeComponent();\n        DataContext = this;\n\n        _blEnty = blEnty;\n\n        _compData = blEnty.ComparisionData;\n\n        // this is a datagrid, whose xaml is cited below\n\n        //ComparisionDataGrid.ItemsSource = _compData;\n    }\n}	0
1146150	1145892	How to force a SqlConnection to physically close, while using connection pooling?	SqlConnection.ClearPool	0
27867652	27867631	How can I make a control on a referenced form accessible?	public string UserName {get {return textBoxUserName.Text;}}	0
10724166	10723967	Generic Factory method to instantiate a derived class from the base class	Type implementationType = typeof(T).Assembly.GetTypes()\n                                   .Where(t => t.IsSubclassOf(typeof(T))\n                                   .Single();\nreturn (T) Activator.CreateInstance(implementationType);	0
16686005	16685911	Implementing a blog entry link	public ActionResult BlogEntry(int year, int month , int day , string title)\n\n    using System;\n    using System.Collections.Generic;\n    using System.Linq;\n    using System.Web;\n     using System.Web.Mvc;\n\n    namespace OurAttributes\n    {\n     public class PopulateTitleDandDateAttribute : ActionFilterAttribute\n     {\n    public override void OnActionExecuting(ActionExecutingContext filterContext)\n    {\n\n                string[] url = filterContext.HttpContext.Request.Uri.split('/');\n                DateTime d = new Date(url[2],url[3],url[4]);\n                if (filterContext.ActionParameters.ContainsKey("createdDate"))\n                {\n                    filterContext.ActionParameters["createdDate"] = d;\n                }\n\n                if (filterContext.ActionParameters.ContainsKey("title"))\n                {\n                    filterContext.ActionParameters["title"] = url[5] ;\n                }\n                base.OnActionExecuting(filterContext);\n\n\n    }\n  }\n }	0
4427504	4427191	How to save date in Excel in date format	double dateDouble = 40461;  \nDateTime dt = DateTime.FromOADate(dateDouble);\n\nstring dateString = dt.ToString();	0
18079648	18079332	Fill table in LaTeX using C#	private string createTable(string[] cols, string[][] values)\n{\n    StringBuilder sb = new StringBuilder();\n    sb.AppendLine(@"\begin{table}[ht]");\n    sb.AppendLine(@"\centering");\n    // Assuming four columns.\n    sb.AppendLine(@"\begin{tabular}{c c c c}");\n    sb.AppendLine(@"\hline\hline");\n    // Column headers.\n    bool first = true;\n    foreach (string col in cols)\n    {\n        if (!first)\n            sb.Append(" & ");\n        sb.Append(col);\n        first = false;\n    }\n    sb.AppendLine();\n    sb.AppendLine(@"\hline");\n    foreach (string[] rowCells in values)\n    {\n        first = true;\n        foreach (string cell in rowCells)\n        {\n            if (!first)\n                sb.Append(" & ");\n            sb.Append(cell);\n            first = false;\n        }\n        sb.AppendLine(@" \\");\n    }\n    sb.AppendLine(@"\hline");\n    sb.AppendLine(@"\end{tabular}");\n    sb.AppendLine(@"\end{table}");\n    return sb.ToString();\n}	0
11310635	11310550	How to get enum value;	var finalValue = ... // 512 -> 1000000010\nvar possibleValues = ... // array of flags [00000001, 000000010, 00000100, 00001000 ... ]\n\nvar appliedFlags = possibleValues.Where(x => x & finalValue == x).ToList();	0
19972898	19972760	Can width of a Gridview's column can be changed in percentage in codebehind?	gvMessageList.Columns[4].HeaderStyle.Width = New Unit(50, UnitType.Percentage);	0
4210389	4210369	Nested loop to add elements of a database to a tree C#	while (rdr.Read())\n{\n    for (int y = 0; y <= numberColumns; y++)         \n    {\n        string childData = rdr[y].ToString();\n        treeView1.Nodes[y].Nodes.Add(childData);\n    }\n}	0
13962050	13961890	Returning a single element from an iterator block - Iterator cannot contain return statement	if(!user.Activated)\n{\n  yield return new ValidationResult("NotActived", Resources.UserNotActivated);\n  yield break;\n}	0
10374422	10374391	Retrieve TcpClient from Hashlist	clientsList[dataFromClient]	0
29167476	29167172	Unity3d how to change GUI text in code	using UnityEngine;\nusing UnityEngine.UI;\n\npublic class FlappyScore : MonoBehaviour{\n\n// Add the Above if you still haven't cause the Text class that you will need is in there, in UnityEngine.UI;\n\npublic Text MyScore;\n\n// Go back to Unity and Drag the "text" GameObject in your canvas to this script.\n\nvoid Start(){\n\n /* if Having difficulty with the above instruction. Un comment this comment block.\nMyScore = GameObject.Find("text").GetComponent<Text>();\n*/\n\n\n  MyScore.text = "50";\n // Your score needs to be casted to a string type.\n\n\n }	0
27291672	26966390	How to create excel type tables in crystal report?	if RecordNumber mod 2 = 0 then Color (234, 234, 234) else crNoColor	0
10691229	10690720	Sorting a ListBox ListItems with LINQ?	List<ListItem> list = new List<ListItem>(lbxCustomers.Items.Cast<ListItem>());\nlist = list.OrderBy(li => li.Text).ToList<ListItem>();\nlbxCustomers.Items.Clear();\nlbxCustomers.Items.AddRange(list.ToArray<ListItem>());	0
18555210	18555064	Read from word document line by line	Application word = new Application();\n    Document doc = new Document();\n\n    object fileName = path;\n    // Define an object to pass to the API for missing parameters\n    object missing = System.Type.Missing;\n    doc = word.Documents.Open(ref fileName,\n            ref missing, ref missing, ref missing, ref missing,\n            ref missing, ref missing, ref missing, ref missing,\n            ref missing, ref missing, ref missing, ref missing,\n            ref missing, ref missing, ref missing);\n\n    String read = string.Empty;\n    List<string> data = new List<string>();\n    for (int i = 0; i < doc.Paragraphs.Count; i++)\n    {\n        string temp = doc.Paragraphs[i + 1].Range.Text.Trim();\n        if (temp != string.Empty)\n            data.Add(temp);\n    }\n    ((_Document)doc).Close();\n    ((_Application)word).Quit();\n\n    GridView1.DataSource = data;\n    GridView1.DataBind();	0
9528983	9528442	How to again recheck the checkbox after deleting some item on btn click?	//here ArrayList contains the ids to match\n         ArrayList a=new ArrayList();\n         a.Add(201105);\n         a.Add(201106);\n         //loop through the items in the datalist\n         for (int i = 0; i < DataList1.Items.Count;i++ )\n         {\n             //check if the list contains the items \n             if (a.Contains(Convert.ToInt32(DataList1.DataKeys[i])))\n             {\n                 (DataList1.Items[i].FindControl("CheckBox1") as CheckBox).Checked = true;\n             }\n         }	0
13618182	13618140	How could I set multi-line text in an Excel textbox using C#	System.Environment.NewLine	0
13759110	13758539	How to buid Expression<Func<T,bool>> from Expression<Func<T>>	static Expression<Func<T,bool>> Munge<T>(Expression<Func<T>> selector)\n{\n    var memberInit = selector.Body as MemberInitExpression;\n    if (memberInit == null)\n        throw new InvalidOperationException("MemberInitExpression is expected");\n    var p = Expression.Parameter(typeof(T), "x");\n\n    Expression body = null;\n    foreach (MemberAssignment binding in memberInit.Bindings)\n    {\n        var comparer = Expression.Equal(\n            Expression.MakeMemberAccess(p, binding.Member),\n            binding.Expression);\n        body = body == null ? comparer : Expression.AndAlso(body, comparer);\n    }\n    if (body == null) body = Expression.Constant(true);\n\n    return Expression.Lambda<Func<T, bool>>(body, p);\n}	0
10455453	10455271	Linq join without equals	var matches = from p in points\n               from r in rectangles\n               where r.Contains(p)\n               select new { r, p };	0
22578002	22577940	replace embded code with querystring value	flashvars='id_video=<%# (Request.QueryString["vid"] != null) ? Request.QueryString["vid"].ToString() : ""%>'	0
22632406	22632331	how to make a text file for logging in c# asp.net	if (!File.Exists("yourfilePath"))\n     File.Create("yourfilePath");\n\nusing (StreamWriter sw = new StreamWriter("yourFilePath", true))\n{\n    sw.WriteLine("logString");        \n}	0
15301084	15300887	Run two winform windows simultaneously	static class Program\n{\n    [STAThread]\n    static void Main()\n    {\n        Application.EnableVisualStyles();\n        Application.SetCompatibleTextRenderingDefault(false);\n\n        var thread = new Thread(ThreadStart);\n        // allow UI with ApartmentState.STA though [STAThread] above should give that to you\n        thread.TrySetApartmentState(ApartmentState.STA); \n        thread.Start(); \n\n        Application.Run(new frmOne());\n    }\n\n    private static void ThreadStart()\n    {\n        Application.Run(new frmTwo()); // <-- other form started on its own UI thread\n    }\n}	0
17499718	17499689	MVC4 Ajax Post Action Parameter Null	data: JSON.stringify({ login : { id: 0, "Username": "myUser", "Password" : "myPass" }}),	0
11894467	11894324	Windows 8 UI: how can I handle right clicks?	event.OriginalSource.DataContext	0
16686371	16685088	Windows Phone ReverseGeocoding to get Address from Lat and Long	List<MapLocation> locations;\n        ReverseGeocodeQuery query = new ReverseGeocodeQuery();\n        query.GeoCoordinate = new GeoCoordinate(47.608, -122.337);\n        query.QueryCompleted += (s, e) =>\n            {\n                if (e.Error == null && e.Result.Count > 0)\n                {\n                    locations = e.Result as List<MapLocation>;\n                    // Do whatever you want with returned locations. \n                    // e.g. MapAddress address = locations[0].Information.Address;\n                }\n            };\n        query.QueryAsync();	0
21915445	21882084	Generating a TreeView hierarchy from a path-like string - C# .NET	private void PopulateTreeView()\n{\n    treeView1.Nodes.Add(AddSubNode(0, new TreeNode("Root")));\n}\n\nprivate TreeNode AddSubNode(int level, TreeNode hierarchy)\n{\n    if (level == StructureArray.Length)\n    {\n        return hierarchy;\n    }\n\n    foreach (string s in StructureData[StructureArray[i]])\n    {\n        tn.Nodes.Add(AddSubNode(level + 1, new TreeNode(s)));\n    }\n    return tn;\n}	0
22589890	22589760	I want to add/remove label dynamically in c sharp	private Label label;  // field on the class (form)\n\nprivate void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n    if (checkBox1.Checked)\n    {\n        label = new Label(); // instantiate new label\n        label.Name = "customLabel";\n        label.AutoSize = true;\n        label.Text = "Dynamically Generated Label";\n        label.Location = new Point(50, 50);\n        label.BringToFront();\n        this.Controls.Add(label);\n    }\n    else\n    {\n        if (label != null) // remove label\n        {\n            this.Controls.Remove(label);\n            label = null;\n        }\n    }\n}	0
1686582	1686540	Sending File in Chunks to HttpHandler	WebClient.UploadData	0
4936909	4936747	InternalsVisibleTo for dynamically generated assembly, but with strong naming	StrongNameKeyPair kp;\n// Getting this from a resource would be a good idea.\nusing(stream = GetStreamForKeyPair())\n{\n    kp = new StrongNameKeyPair(fs);\n}\nAssemblyName an = new AssemblyName();\nan.KeyPair = kp;\nAssemblyBuilder ab = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.RunAndSave);	0
27878055	27877971	Accessing constants using string variable	public static class Foo\n{\n    private static Dictionary<string,string> m_Constants = new Dictionary<string,string>();\n\n    static Foo()\n    {\n        m_Constants["Foo"] = "Hello";\n        // etc\n    }\n\n    public static string GetConstant( string key )\n    {\n        return m_Constants[key];\n    }\n}\n\npublic string Bar( string constName )\n{\n    return Foo.GetConstant( constName );\n}	0
16680789	16680775	How to sort List<Point>	pointsOfList = pointsOfList.OrderByDescending(p => p.X).ToList();	0
12899255	12899138	Monitoring Process Exits in a Custom Action	Process.WaitForExit()	0
15365962	15364264	C# DragDrop from toolStrip	public Form1() {\n  InitializeComponent();\n  toolStripButton1.MouseDown += toolStripButton_MouseDown;\n  toolStripButton2.MouseDown += toolStripButton_MouseDown;\n\n  panel1.DragEnter += panel1_DragEnter;\n  panel1.DragDrop += panel1_DragDrop;\n}\n\nvoid toolStripButton_MouseDown(object sender, MouseEventArgs e) {\n  this.DoDragDrop(sender, DragDropEffects.Copy);\n}\n\nvoid panel1_DragEnter(object sender, DragEventArgs e) {\n  e.Effect = DragDropEffects.Copy;\n}\n\nvoid panel1_DragDrop(object sender, DragEventArgs e) {\n  ToolStripButton button = e.Data.GetData(typeof(ToolStripButton))\n                           as ToolStripButton;\n  if (button != null) {\n    if (button.Equals(toolStripButton1)) {\n      MessageBox.Show("Dragged and dropped Button 1");\n    } else if (button.Equals(toolStripButton2)) {\n      MessageBox.Show("Dragged and dropped Button 2");\n    }\n  }\n}	0
15598505	15598467	Find a list by its name C#	//Create global dictionary of lists\nDictionary<string, List<string> dictionaryOfLists = new Dictionary<string, List<string>();\n\n//Get and create lists from a single method\npublic List<string> FindListByName(string stringListName)\n{\n    //If the list we want does not exist yet we can create a blank one\n    if (!dictionaryOfLists.ContainsKey(stringListName))\n        dictionaryOfLists.Add(stringListName, new List<string>());\n\n    //Return the requested list\n    return dictionaryOfLists[stringListName];\n}	0
29166063	29165884	How to implement passing of parameter to a StreamedPipeline that uses Action<Stream,Stream>	var additionalCompressionArgument = 123;\nusing (FileStream input = File.OpenRead("inputData.bin"))\nusing (FileStream output = File.OpenWrite("outputData.bin"))\nusing (StreamPipeline pipeline = new StreamPipeline(\n   (input, output) => Compress(input, output, additionalCompressionArgument), \n    Encrypt))\n{\n    pipeline.Run(input, output);\n}\n\nstatic void Compress(Stream input, Stream output, int additionalCompressionParameter){\n    using (GZipStream compressor = new GZipStream(\n           output, CompressionMode.Compress, true))\n        CopyStream(input, compressor);\n}	0
4894672	4894655	Rounding off a float/double conditionally	string stFloat = String.Format("{0:0.0000}", FLOAT_VALUE);	0
29123599	29123196	DataGridView inside a panel jumps to beginning of list after panel gets scrolled	public class PanelEx : Panel {\n  protected override Point ScrollToControl(Control activeControl) {\n    //return base.ScrollToControl(activeControl);\n    return this.AutoScrollPosition;\n  }\n}	0
24528915	24528533	Smooth drawing or painting of child controls in Panel while scrolling	public partial class SmoothScrollPanel : UserControl\n{\n    public SmoothScrollPanel()\n    {\n        InitializeComponent();\n        // this.DoubleBuffered = true;\n    }\n\n    private const int WM_HSCROLL = 0x114;\n    private const int WM_VSCROLL = 0x115;\n\n    protected override void WndProc(ref Message m)\n    {\n        if ((m.Msg == WM_HSCROLL || m.Msg == WM_VSCROLL)\n        && (((int)m.WParam & 0xFFFF) == 5))\n        {\n            // Change SB_THUMBTRACK to SB_THUMBPOSITION\n            m.WParam = (IntPtr)(((int)m.WParam & ~0xFFFF) | 4);\n        }\n        base.WndProc(ref m);\n    }\n\n    protected override CreateParams CreateParams\n    {\n        get\n        {\n            var cp = base.CreateParams;\n            cp.ExStyle |= 0x02000000;    // Turn on WS_EX_COMPOSITED\n            return cp;\n        }\n    }\n}	0
27394747	27394708	Convert string of data points separated by comma to List<int> in C#	string s="23,234,0,12,43,6,34,45,7";\n\nstring[] s = data.Split(',');\n\nList<int32> li = new List<int32>();\n        foreach (String sout in s)\n        {\n            int i;\n            if (Int32.TryParse(sout, out i))\n                li.Add(i);\n        }	0
34323705	34323452	Website can only search or sort data from a database	//declare your variable.  I added a connection and command so I can include parameters in the process.\nstring orderBy = "";\nstring whereClause = "";\nstring sql = "";\n\n//create your order by clause\nswitch (Request["sort"])\n{\n    case "PriceASC":\n        orderBy = "order by Product_Price ASC";\n        break;\n    case "PriceDESC":\n        orderBy = "order by Product_Price DESC";\n        break;\n    default:\n        orderBy = "ORDER BY Product_ID";\n        break;\n}\n\n//create your where clause.  \nif (!string.IsNullOrEmpty(Request["search"])) // forgot the ! here\n{\n    whereClause = string.Format(" where Product_Keywords like '%{0}%'", Request["search"]); // very unsafe to plug this in.  should use parameter\n\n}\n\nsql = string.Format("SELECT * FROM Products{0} {1}",whereClause, orderBy); //build your query string.  if no search parameter was given the where clause will be blank, but the order by will still exist.\n\n@foreach (var row in db.Query(sql))\n{\n    //some code here\n}	0
19855174	19855013	XML get people where date starts with 2013	string year = "2013";\n\nprotected List<string> GetPersons(string year)\n{\n    XElement company= XElement.Load(Server.MapPath(XMLfil));\n\n    var persons= (from a in company.Elements("department").Elements("people").Elements("person")\n                  where (string)a.Element("gender").Value == 'male' && (string)a.Element("datum").Value.StartsWith(year)\n                  select (string)(a.Element("age"))).ToList<string>();\n    return persons;\n}	0
8231022	8230873	PostSharp - OnExceptionAspect - Get line number of exception	var st = new StackTrace(ex, true);\nvar frame = st.GetFrame(0); //Not sure if 0 is correct index, but try it first\nvar line = frame.GetFileLineNumber();	0
28506857	28506617	get my dhcp server ip address	Console.WriteLine("DHCP Servers");\nNetworkInterface[] adapters  = NetworkInterface.GetAllNetworkInterfaces();\nforeach (NetworkInterface adapter in adapters)\n{\n\n    IPInterfaceProperties adapterProperties = adapter.GetIPProperties();\n    IPAddressCollection addresses = adapterProperties.DhcpServerAddresses;\n    if (addresses.Count >0)\n    {\n        Console.WriteLine(adapter.Description);\n        foreach (IPAddress address in addresses)\n        {\n            Console.WriteLine("  Dhcp Address ............................ : {0}", \n                address.ToString());\n        }\n        Console.WriteLine();\n    }\n}	0
31027636	31027507	how to track multiple values from a method	var d = new List<Tuple<string, double>>();\n.\n.\n.\nwhile ((line = file.ReadLine()) != null)\n{\n    d.Add(Tuple.Create(line, p.calculate_CS(line, document)));\n}\n.\n.\n.\nforeach (double item in d.OrderByDescending(t => t.Item2))\n{\n    fileW.WriteLine("{0} from line {1}", item.Item2, item.Item1);\n}	0
9986438	9986422	Displaying only free time slots which haven't been booked for any date	AND apptDate = thepassedindate	0
14841959	14841932	Access a page only if valid login	[Authorize]	0
12749606	12749394	Compare / Search Text Files Line by Line Search for particular words	string[] filea = File.ReadAllLines("test.txt");\nforeach (var s in filea)\n{\n    string[] parts = s.Split(':');\n\n    if (parts.Length == 2)\n    {\n        if (parts[0].Contains("Email"))\n            richTextBox1.AppendText(parts[1].Trim());\n\n        if (parts[0].Contains("Status"))\n            richTextBox1.AppendText(":" + parts[1].Trim() + Environment.NewLine);\n    }\n}	0
11562615	11562518	Remove Border from Linklabel C#	this.label.BorderStyle = System.Windows.Forms.BorderStyle.None	0
15597812	15591392	How to Update Database Table after AjaxFileUpload ASP.NET	string getfile="";\nfoeach(string f in Directory.GetFiles(Server.MapPath("~/"+str+"/"))\n{\n  getfiles= getfiles + f + ",";\n }	0
17298507	17298353	How can I extract a string between <strong> tags usings C#?	Regex regex = new Regex("<strong>(.*)</strong>");\n  var v = regex.Match("Unneeded text <strong>Needed Text</strong> More unneeded text");\n  string s = v.Groups[1].ToString();	0
3201624	3201598	How do I create a file AND any folders, if the folders don't exist?	// Determine whether the directory exists.\nif (Directory.Exists(path)) \n{\n    Console.WriteLine("That path exists already.");\n    return;\n}\n\n// Try to create the directory.\nDirectoryInfo di = Directory.CreateDirectory(path);\nConsole.WriteLine("The directory was created successfully at {0}.",\n    Directory.GetCreationTime(path));	0
9511547	9511158	autoincrementing alphanumeric id for a table based on unique id of another table	create table students(id varchar(10) primary key not null, Department varchar(2), Name varchar(80))\ngo\n\ncreate trigger students_insert_PK\n    on students\n    INSTEAD OF INSERT\nas\n    declare @id int;\n    declare @dept varchar(2); select @dept=Department from INSERTED;\n    select @id=cast(max(right(id,4)) as int) from students where Department=@dept;\n    set @id=isnull(@id,0)+1;\n\n    insert into students\n    select Department+right('0000'+cast(@id as varchar(4)),4)\n    , Department\n    , name\n    from INSERTED;\ngo\n\ninsert into students (Department,Name) values ('CS','John');\ninsert into students (Department,Name) values ('CS','Pat');\ninsert into students (Department,Name) values ('CS','Sheryl');\ninsert into students (Department,Name) values ('IT','Phil');\ninsert into students (Department,Name) values ('EE','Frank');\ninsert into students (Department,Name) values ('EE','Amy');\ninsert into students (Department,Name) values ('EE','Stu');\ngo\n\nselect * from students;\ngo	0
12624692	12624669	C# Regex Replace using match value	html = html.Replace(ItemMatch.Value, "<h2>My Partial View</h2>");	0
13178767	13178752	Current date without time	String test = DateTime.Now.ToString("dd.MM.yyy");	0
1609257	1609231	Lambda Expression	var project = accounts.Select(a => a.AccountProjects)\n                      .Where(x => x.AccountProjectID == accountProjectId);	0
7146418	7146355	Updating a property within a list where another property condition is met	myList.ForEach(x => x.IsUnread = (x.UnreadCount > 0));	0
24230037	24229994	Insert into two tables with no relationships	public class CreateArtistViewModel\n{\n    public string ArtistName { get; set; }\n    public int? Genres { get; set; } // if you provide chooser for user\n    public string GenresName { get; set; } // if user can enter new genre\n    public string GenresDecription { get; set; } // if user can enter new genre\n\n    public IList<Genre> Genres { get; set; }\n}	0
16939894	16939483	Update UI from Task Parallel Library issue	int i = 0, flag = 5;\nvar uiScheduler = TaskScheduler.FromCurrentSynchronizationContext();\nTask.Factory.StartNew(() =>\n{\n    while (i < flag)\n    {\n        Task.Factory.StartNew(() =>\n        {\n            this.Text = i.ToString();\n        }, System.Threading.CancellationToken.None, TaskCreationOptions.None, uiScheduler);\n        i++;\n        System.Threading.Thread.Sleep(1000);\n\n    }\n}); // <---- Removed arguments (specifically uiScheduler)	0
10234191	10233924	Using a SQL Server database file	//SQL Connection stuff here\ncon.Open();\nString queryStr = "SELECT name FROM bbc WHERE name LIKE '*%'";\nSqlCommand com = new SqlCommand(queryStr, con);\nSqlDataReader sdr = com.ExecuteReader();\n\nwhile(sdr.Read())\n{\n   this.textbox2.Text = sdr.GetValue(0).ToString();\n}	0
22797869	22797492	WPF read an XML attribute	string xml = @"<MyApp version='1.01'>\n   <MySettings>\n      <Setting1>1</Setting1>\n      <Setting2>2</Setting2>\n   </MySettings>\n </MyApp>";\n var doc= XDocument.Parse(xml);\nvar settings = doc.Descendants("MyApp")\n                  .Where(x => (string)x.Attribute("version") == "1.0")\n                  .Descendants("MySettings")\n                  .Elements()\n                  .ToDictionary(x => x.Name.ToString(), x => (string)x);	0
4317823	4317763	listview to string exception thrown	double price = 0.0;\n    foreach ( ListViewItem item in breakfast )\n    {\n        price += Double.Parse(item.SubItems[1].Text);\n    }	0
6137789	6132693	Regular Expression to parse string url links	string pattern= "\b(?<protocol>https?|ftp|gopher|telnet|file|notes|ms-help)://(?<domain>[-A-Z0-9.]+)(?<file>/[-A-Z0-9+&@#/%=~_|!:,.;]*)?(?<parameters>\?[-A-Z0-9+&@#/%=~_|!:,.;]*)?"	0
9772932	9772686	How to write a generic conversion method which would support converting to and from nullable types?	public static T To<T>(this object value)\n{\n    Type t = typeof(T);\n\n    // Get the type that was made nullable.\n    Type valueType = Nullable.GetUnderlyingType(typeof(T));\n\n    if (valueType != null)\n    {\n        // Nullable type.\n\n        if (value == null)\n        {\n            // you may want to do something different here.\n            return default(T);\n        }\n        else\n        {\n            // Convert to the value type.\n            object result = Convert.ChangeType(value, valueType);\n\n            // Cast the value type to the nullable type.\n            return (T)result;\n        }\n    }\n    else \n    {\n        // Not nullable.\n        return (T)Convert.ChangeType(value, typeof(T));\n    }\n}	0
10505814	10505486	DirectorySearcher.Filter return Users with birthday of current month	int now = DateTime.Now.Month;\n                string month;\n                if (now < 10)\n                {\n                    month = "0" + now.ToString();\n                }\n                else\n                {\n                    month = now.ToString();\n                }\n\nmySearcher.Filter = ("(&(objectClass=user)(|(employeeHireDate=" + month + "*)(employeeBirthDate=" + month + "*)))");	0
7483931	7483877	How to know the number of Files opened by OpenFileDialog	openFileDialog1.FileNames.Length	0
33779084	33760115	Outlook mailing application c#	Microsoft.Office.Interop.Outlook.Inspector oInspector = oMsg.GetInspector;	0
4907746	4744384	how to set value in DataGridViewComboBoxColumn from a datatable?	int i=0; \n foreach (DataRow dgvr in  _ds.Tables[0].Rows )\n                {\n                    grvPackList.Rows[i].Cells["Units"].Value = dgvr["Units"].ToString();\n                    i++;\n                }	0
10221447	10221389	Replacing value in string depending on inner value	// this is a MatchEvaluater for a regex replace\nstring me_setFormatValue(Match m){\n    // this is the key for the value you want to pull from the database\n    // Job_Number, etc...\n    string key = m.Groups[1].Value;\n\n    return SomeFunctionToGetValueFromKey(key);\n}\n\n\nvoid testMethod(){\n    string format_string = @"No: {Job_Number}\nCustomer: {Cust_Name}\nAction: {Action}";\n\n    string formatted = Regex.Replace(@"\{([a-zA-Z_-]+?)\}", format_string, me_SetFormatValue);\n}	0
1718196	1718090	How to get the array cell position when using foreach across an array?	foreach (var item in Items.Select((elem, index) => new { Item = elem, Index = index }))\n{\n    DoStuff(item.Item, item.Index);\n}	0
33616048	33614955	Efficient way to filter IEnumerable and serilize it to JSON in .NET	var result1 = new\n{\n    draw = Draw,\n    recordsTotal = persons.Count(),\n    recordsFiltered = (iDisplayLength - iDisplayStart),\n    data = persons\n        .Where(p => InString(p.FName) || InString(p.LName) || InString(p.Id.ToString()) || InString(p.Email))\n        .Select(p => new { Email = p.Email }) //already a list, does not need to be an array of objects\n        .Skip(iDisplayStart)   \n        .Take(iDisplayLength)\n        .ToList() //execute\n};\n\n//also consider an extension method\npublic bool InString(string prop, string search)\n{\n    return prop.Contains(search, StringComparison.OrdinalIgnoreCase)\n}	0
16520243	16519610	How to color vertices?	GL.VertexAttribPointer((int)GLKVertexAttrib.Color,\n                           3, VertexAttribPointerType.Float,\n                           false, 0, 0);	0
6307152	6306465	search box with database	List<string> namesCollection = new List<string>();\nSqlConnection conn = new SqlConnection();\nconn.ConnectionString = 'Connexion String or From File'\nSqlCommand cmd = new SqlCommand();\ncmd.Connection = conn;\ncmd.CommandType = CommandType.Text;\ncmd.CommandText = "Select distinct [Name] from [Names] order by [Name] asc";\nconn.Open();\nSqlDataReader dReader = cmd.ExecuteReader();\nif (dReader.HasRows == true)\n{\n   while (dReader.Read())\n   namesCollection.Add(dReader["Name"].ToString());\n}\ndReader.Close();\n\ntxtName.AutoCompleteMode = AutoCompleteMode.Suggest;\ntxtName.AutoCompleteSource = AutoCompleteSource.CustomSource;\ntxtName.AutoCompleteCustomSource = namesCollection;	0
1066177	1066131	How to programmatically change Active Directory password	using (var context = new PrincipalContext( ContextType.Domain ))\n{\n  using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))\n  {\n      user.SetPassword( "newpassword" );\n      // or\n      user.ChangePassword( "oldPassword", "newpassword" );\n  }\n}	0
34091207	34090980	Application doesn't quit	SyncNotification=true	0
29710033	29709966	Replace a specific item in IEnumerable<string>	m_oEnum  = m_oEnum.Select(s => s == "abc" ? "abc-test" : s).ToArray();	0
4498584	4497050	Make new row dirty programmatically and insert a new row after it in DataGridView	myGrid.NotifyCurrentCellDirty(true);	0
3297457	3297161	Changing CultureInfo of Main thread from worker thread	MainForm.Invoke(helperMethod)	0
9632281	9629118	Copy resources from c# pjct to a windows directory	File.Copy(@"Resources\install.bat", @"C:\directory\install.bat");	0
31860992	31850453	Tree filtering performance	- Create new cache (bottom up, top down)\n- Foreach CachedObject\n- Check if items exist (both parent and child)\n     : yes -> select node\n     : no -> create node and insert it in the new cache\n - add child to parent node	0
11999545	11999235	Entity Framework: map varchar to DateTime property	[Table("webnews_in")]\npublic class WEBNews_in : AbsNews {\n\n   private DateTime _inDateTimeAdded = DateTime.MinValue;\n\n   public string InDateTimeAdded {\n       get {\n           return Format(_inDateTimeAdded, " dd/MM/yyyy hh:mm:ss tt");\n       }\n       set {\n           _inDateTimeAdded = DateTime.Parse(value);\n       }\n   }\n\n   private DateTime _inDateTimeUpdated = DateTime.MinValue;\n\n   public string InDateTimeUpdated {\n       get {\n           return Format(_inDateTimeUpdated, " dd/MM/yyyy hh:mm:ss tt");\n       }\n       set {\n           _inDateTimeUpdated = DateTime.Parse(value);\n       }\n   }\n}	0
17332561	17332093	How to have an XML file in my App?	var myFile = MyApp.Resources.AppResources.myFile;\n\n        StringReader sr = new StringReader(myFile);\n        var xmlSerializer = new XmlSerializer(typeof(Foo));\n        var classInstance = xmlSerializer.Deserialize(sr);	0
30802481	30801711	Individual Character Boxing Crystal Reports	declare @string varchar(16)\nset @string = 'abcdefghijklmnop'\n\nSELECT\nLEFT(@string,1),\nRIGHT(LEFT(@string,2),1),\nRIGHT(LEFT(@string,3),1),\nRIGHT(LEFT(@string,4),1),\nRIGHT(LEFT(@string,5),1),\nRIGHT(LEFT(@string,6),1),\nRIGHT(LEFT(@string,7),1),\nRIGHT(LEFT(@string,8),1),\nRIGHT(LEFT(@string,9),1),\nRIGHT(LEFT(@string,10),1),\nRIGHT(LEFT(@string,11),1),\nRIGHT(LEFT(@string,12),1),\nRIGHT(LEFT(@string,13),1),\nRIGHT(LEFT(@string,14),1),\nRIGHT(LEFT(@string,15),1)	0
18013978	18013853	The best practice to design one to many relationship in EF code first	public class Student \n   {\n      public int StudentId { get; set; }\n      public int StudentName { get; set; }\n      public int StudentRoll { get; set; }\n\n      public int DepartmentId { get; set; }\n      public virtual Department Department { get; set; }\n   }\n\n   public class Department \n   {\n      public int DepartmentId { get; set; }\n      public int DepartmentName { get; set; }\n\n      public virtual ICollection<Student> Students { get; set; } \n   }	0
3369339	3368970	How to populate a ToolStripComboBox?	ToolStripComboBox1.ComboBox.ValueMember = "YourValueField";	0
31810405	31809969	How to write ListView TextBox Items to Database for each row	List<ListViewDataItem> lItems = fundingListView.Items.ToList();\n\n        foreach(ListViewDataItem item in lItems)\n        {\n            TextBox tb = item.FindControl("fundingConfirmationAmount") as TextBox;\n            string addToDatabase = tt.Text;\n\n        }	0
28501268	28501032	Check if a number in a string contains a valid year in c#	using System;\nusing System.Text.RegularExpressions;\n\npublic class Program\n{\n    public static void Main()\n    {\n        Regex regex = new Regex(@"\d{4}");\n        Match match = regex.Match("Payment for the month ending 30 Nov 2014");\n        if (match.Success)\n        {\n            Console.WriteLine(match.Value);\n        }\n    }\n}	0
17049163	17049086	How to get data from an int pointer to a memory stream in c#?	using (System.IO.UnmanagedMemoryStream memoryStream = new UnmanagedMemoryStream(pointer, length, length, FileAccess.Read))\n{\n    byte[] imageBytes = new byte[length];\n    memoryStream.Read(imageBytes, 0, length);\n}	0
11801968	11801905	Binding to dependencyproperty on a per object basis	public static DependencyProperty Thickness = \n    DependencyProperty.Register("Thickness", typeof(double), typeof(Test));	0
11523693	11523565	enable and disable menu items of mdiparent from loginform in c#	mnuLogin_Click()\n{\nFrmLogin frmLogin = new FrmLogin();\nif(frmLogin.ShowDialog() == DialogResult.OK)\n{\n//Enable menu here.\n}\n}	0
3535303	3535010	ListBox with pop-out/popup item details	toolTip.PlacementTarget = yourSelectedItem;\n        toolTip.Placement = PlacementMode.Right;\n        toolTip.Content = {place whatever you need to display here};	0
29831758	29831343	Parsing JToken to get Key Value pair	foreach (var entry in json["feed"]["entry"])\n        {\n            var title = (string)entry.SelectToken("title.$t");\n        }	0
16158633	16158521	How access bool from other form/script?	public static bool isTrue = true;	0
31227047	31227001	Understanding in string concatenation	static void Main(string[] args)\n    {\n        bool a = true;\n        bool b = true;\n        bool c = true;\n        string x = "";\n        string Test = x + (a ? "Clear" : "") + (b ? "Permanent" : "") + (c ? "Salaried" : "");\n        Console.WriteLine(Test);\n\n        Console.ReadLine(); //so that my console window doesn't close\n\n    }	0
18405711	18403999	WP - how to remove underline in hyperlinkButton programmatically?	var str =   "<ControlTemplate TargetType=\"HyperlinkButton\" xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\">" +\n            "   <TextBlock HorizontalAlignment=\"{TemplateBinding HorizontalContentAlignment}\" Text=\"{TemplateBinding Content}\" VerticalAlignment=\"{TemplateBinding VerticalContentAlignment}\"/>" +\n            "</ControlTemplate>";\n\nvar template = (ControlTemplate)XamlReader.Load(str);  \n\nHyperlinkButton hyperlinkButton = new HyperlinkButton()\n{\n    Content = "Click me",\n    HorizontalAlignment = HorizontalAlignment.Left,\n    NavigateUri = new Uri("http://my-link-com", UriKind.Absolute),\n    Template = template\n};	0
16326506	16320338	Dynamically filter and resize context menu c# while keeping its gravity to bottom	private Rectangle lastBounds;\n\n    private void contextMenuStrip1_Opened(object sender, EventArgs e)\n    {\n        lastBounds = contextMenuStrip1.Bounds;\n    }\n\n    private void contextMenuStrip1_SizeChanged(object sender, EventArgs e)\n    {\n        Rectangle rc = contextMenuStrip1.Bounds;\n        int diff = lastBounds.Height - rc.Height;\n        if (diff > 0)\n        {\n            contextMenuStrip1.Bounds = new Rectangle(new Point(rc.X, rc.Y + diff), rc.Size);\n            lastBounds = contextMenuStrip1.Bounds;\n        }\n        else\n        {\n            contextMenuStrip1.Bounds = new Rectangle(new Point(rc.X, rc.Y - diff), rc.Size);\n            lastBounds = contextMenuStrip1.Bounds;\n        }\n    }	0
8536373	8526375	Finding a child control inside a templated usercontrol	protected void Page_PreRender(object sender, EventArgs e)\n{\n    Literal1.Text = "Hello, World";\n}	0
2616183	2616177	How to assign a value of a property to a var ONLY if the object isn't null	string name = SomeUserObject != null ? SomeUserObject.Username : string.Empty;	0
15761070	15760257	want to stop user input by messagebox but bypassed by a Enter keydown	System.Media.SystemSounds.Beep.Play();	0
25029435	23075609	WPF MediaElement Video freezes	try\n        {\n            var hwndSource = PresentationSource.FromVisual(this) as HwndSource;\n            var hwndTarget = hwndSource.CompositionTarget;\n            hwndTarget.RenderMode = RenderMode.SoftwareOnly;\n        }\n        catch (Exception ex)\n        {\n            Log.ErrorException(ex.Message, ex);\n        }	0
8986629	8986476	Fit image to a bounding box and fill the rest with black in C#	g.DrawImage(res, p);            \n        //left\n        g.FillRectangle(Brushes.Black, new Rectangle(0, 0, p.X, dest_size.Height));\n        //right\n        g.FillRectangle(Brushes.Black, new Rectangle(p.X + act_size.Width, 0, p.X, dest_size.Height));\n        //up\n        g.FillRectangle(Brushes.Black, new Rectangle(0, 0, dest_size.Width, p.Y));\n        //down\n        g.FillRectangle(Brushes.Black, new Rectangle(0, p.Y + act_size.Width, dest_size.Width, p.Y));	0
6827412	6827356	C# RegEx pattern for scheduler (date / time alike pattern matcher)	(\*|[0-6])\s+(\*|[0-2]\d|3[01])\s+([01]\d|2[0-3])\s+(00|15|30|45)	0
30151850	30011614	Convert excel file to jpg in c#	Workbook workbook = new Workbook(@"D:\a.xlsm");\n            //Get the first worksheet.\n            Worksheet sheet = workbook.Worksheets[12];\n\n            //Define ImageOrPrintOptions\n            ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();\n            //Specify the image format\n            imgOptions.ImageFormat = System.Drawing.Imaging.ImageFormat.Jpeg;\n            //Only one page for the whole sheet would be rendered\n            imgOptions.OnePagePerSheet = true;\n\n            //Render the sheet with respect to specified image/print options\n            SheetRender sr = new SheetRender(sheet, imgOptions);\n            //Render the image for the sheet\n            Bitmap bitmap = sr.ToImage(0);\n\n            //Save the image file specifying its image format.\n            bitmap.Save(@"d:\SheetImage.jpg");	0
20409226	20408968	Edit XML node in c#	XmlElement itemTitle = (XmlElement)doc.SelectSingleNode("/configuration/car[@title = '" + var_x + "']");\n XmlNode itemUrl = doc.SelectSingleNode("/configuration/car[@title = '" + var_x + "']/url");\n\n itemTitle.Attributes["title"].Value = texbox_title.Text;\n itemUrl.InnerText = textbox_url.Text;	0
30726409	30706917	Setting a value to a field in XPO	private void ProcessSelectedObject(System.Collections.IList list)\n    {\n        foreach (object obj in list)\n        {\n            if (obj is Contact)\n            {\n                if (((Contact)obj).Sector == null)\n                {\n                    ((Contact)(obj)).Sector = "Default";\n                }\n            }\n        }\n     }	0
9594361	9594293	How to display the current time on a wp7 application?	DispatcherTimer dt = new DispatcherTimer();\n        dt.Interval = TimeSpan.FromMilliseconds(1000);\n\n        dt.Tick += (s, e) => { currentTime.Text = DateTime.Now.ToShortTimeString(); };\n\n        dt.Start();	0
32737375	32737246	Sort a list by className Alphabetic order	items = items.OrderBy(x => x.GetType().Name).ToList();	0
14400266	14400134	Fluent nhibernate mapping	public bool IsDefaultPrice\n{\n    get\n    {\n         return price1 == 0 && price2 == 0;\n    }\n}	0
9106943	9104950	Index of the current row in DataGridView	produseDataGridView.Rows(Index + 1).Selected = True;\nproduse_magazinDataGridView.Rows(Index1 + 1).Selected = True;	0
24580427	24542990	Create XML DOC from API using foreach	var doc = new XDocument(\n  new XElement("SEITOrders",\n  from o in apiCall.ApiResponse.OrderArray.ToArray()\n  select \n  new XElement("order", \n  new XElement("orderID", o.OrderID))));	0
10172573	10172501	Query with parameter	SqlCommand com = new SqlCommand("SELECT id, nome, sigla FROM  pais WHERE (estado=@estado)", connection);\ncom.Parameters.Add(new SqlParameter("estado", value)); \n        SqlDataAdapter cidadeTableAdapter = new SqlDataAdapter();\n        cidadeTableAdapter.SelectCommand = this.com;\n        DataSet set = new DataSet("return");\n        cidadeTableAdapter.Fill(set);\n        this.com.Connection.Close();\n        return set;	0
14844271	14844150	Create a web browser with tab capability	private void button_addTab_Click(object sender, EventArgs e)\n        {\n            TabPage addedTabPage = new TabPage("tab title"); //create the new tab\n            tabControl_webBrowsers.TabPages.Add(addedTabPage); //add the tab to the TabControl\n\n            WebBrowser addedWebBrowser = new WebBrowser()\n            {\n                Parent = addedTabPage, //add the new webBrowser to the new tab\n                Dock = DockStyle.Fill\n            };\n            addedWebBrowser.NewWindow += specificWebBrowser_NewWindow;\n            addedWebBrowser.Navigate("www.google.com");\n        }	0
27567240	27566402	Get the token of a closed uncreated generic method	// If the to be called method is generic...\nvar methodInfo = Type.GetType("System.Reflection.Emit.ModuleBuilder")\n                    .GetTypeInfo()\n                    .DeclaredMethods\n                    .Where((method) => method.Name == "GetMethodTokenInternal" && method.GetParameters().Length == 3)\n                    .First();\nint token = \n    (int)methodInfo.Invoke(_moduleBuilder, new object[] { closedGenericMethod, null, false });	0
16648066	16648040	selecting data where column='null'	SqlDataAdapter dba = new SqlDataAdapter(@"SELECT * from [tblCountries] \n                                     WHERE [Continent] IS NULL order by [Common Name]", connection);\n            dba.Fill(ds);\n            drpNonAfricanCountries.DataSource = ds;	0
30087310	30049326	How to move an 2D character(with animation) to mouse click position in C#?	if (Input.GetMouseButtonDown (0)) {\n    target = Camera.main.ScreenToWorldPoint (Input.mousePosition);\n    target.z = transform.position.z;\n    if(target.x > transform.position.x) transform.localScale = new Vector3(1, 1, 1); \n    else if(target.x < transform.position.x) transform.localScale = new Vector3(-1, 1, 1);\n    anim.SetInteger ("Direction", 1);\n } \n transform.position = Vector3.MoveTowards(transform.position, target, speed * Time.deltaTime);	0
8270026	8269923	Simple Paging in datalist as in GridView - NOT CUSTOM PAGING	// Populate the repeater control with the Items DataSet\nPagedDataSource objPds = new PagedDataSource();\nobjPds.DataSource = Items.Tables[0].DefaultView;\n\n// Indicate that the data should be paged\nobjPds.AllowPaging = true;\n\n// Set the number of items you wish to display per page\nobjPds.PageSize = 3;\n\n// Set the PagedDataSource's current page\nobjPds.CurrentPageIndex = CurrentPage - 1;\n\nrepeaterItems.DataSource = objPds;\nrepeaterItems.DataBind();	0
19494697	19494318	how I can use my defined method in a dataset?	DataSet1TableAdapters.PersonTableAdapter adapter = new DataSet1TableAdapters.PersonTableAdapter;\nadapter.InsertQuery(...) // <-- my method haha!	0
22985100	22984904	Can you make a full clone of Winforms ComboBox.ObjectCollection	var tmpItems = comboBoxKey.Items\n            .Cast<Object>()\n            .ToArray();\ncomboBoxKey.Items.Clear();\nString tmp2 = textBoxSearchKey.Text;\n\nvar filteredItems = tmpItems.Where(x=> x.ToString().Contains(tmp2))\n                            .ToArray();\ncomboBoxKey.Items.AddRange(filteredItems );	0
16212615	16212478	How to get the intermediate portion of string?	string output= input.Substring(input.IndexOf('.') + 1, \n                  input.LastIndexOf('.') - input.IndexOf('.') - 1);	0
28921214	28921132	Accessing a external browser with c#	string url = 'http://...';\nWebClient client = new WebClient ();\nstring content = client.DownloadString(url);\n\n// And now you can search\nif (content.Contains("Zyak"))\n{\n    ...\n}	0
12260745	12260631	Converting IF statements to simple statement - Which one is efficient?	item.Imported	0
1026674	1026636	Why is my UDPClient null once in a while	using (UdpClient udpLink = new UdpClient(ipAddress, 514))\n{\n    udpLink.Send(rawMsg, rawMsg.Length);\n}	0
13666446	13666199	Recursive Function to calculate factorial using PLINQ	public long RecursivePLINQ(long factor,long total)\n    {\n\n        if(total == 0)\n        {\n            total = 1;\n        }\n        if (factor > 1)\n        {\n            Parallel.For<long>(0, 1, () => factor, (j, loop, factorial) =>\n            {\n                Thread.Sleep(1);    /*Simulate Moderate Operation*/\n                total = factorial * RecursivePLINQ(--factorial, total);\n                return total;\n            }, (i) =>  {return;});\n        }\n        return total;\n    }	0
2696704	2696691	Can I get the method local variables through a stack trace in C#?	MethodInfo mi = typeof(Example).GetMethod("MethodBodyExample");\nMethodBody mb = mi.GetMethodBody();\nConsole.WriteLine("\r\nMethod: {0}", mi);\n\n// Display the general information included in the \n// MethodBody object.\nConsole.WriteLine("    Local variables are initialized: {0}", \n    mb.InitLocals);\n\nforeach (LocalVariableInfo lvi in mb.LocalVariables)\n{\n    Console.WriteLine("Local variable: {0}", lvi);\n}	0
16781146	16781118	Set default value for auto-implemented property	public class MyClass\n{\n    public MyClass()\n    {\n        Foo = 1;\n    }\n\n    public int Foo { get; set; }\n}	0
15000970	14979080	How to insert values to excel cells using a Windows Service C#	string path = @"C:\ProjectTesting\TwsDde.xlsm";\n\n        oXL = new Microsoft.Office.Interop.Excel.Application();\n\n        oXL.Visible = true;\n\n        oXL.DisplayAlerts = false;\n\n        mWorkBook = oXL.Workbooks.Open(path, 0, false, 5, "", "", false, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "", true, false, 0, true, false, false);\n\n        //Get all the sheets in the workbook\n\n        mWorkSheets = mWorkBook.Worksheets;\n\n        //Get the allready exists sheet\n\n        mWSheet1 = (Microsoft.Office.Interop.Excel.Worksheet)mWorkSheets.get_Item("Basic Orders");\n\n        Microsoft.Office.Interop.Excel.Range range= mWSheet1.UsedRange;\n\n        mWSheet1.Cells[12, 1] = "bla bla bla";	0
31539926	31539338	how to convert short to byte array in Objective-c?	char* short_to_byteArr (short value)\n{\n   static char byte_arr[] = {};\n   byte_arr[0] = value & 0x00FF;\n   byte_arr[1] = (value>>8) & 0x00FF;\n   return byte_arr;\n}	0
5698328	5698294	What's the proper way to determine whether a certain URL sits within a certain directory?	Request.Url.AbsolutePath	0
19445330	19445236	Add value to generic dictionary by key	foreach (var item in records)\n{\n    string category = item.Description\n                          .Split(new char[] { '|' })[1]\n                          .Trim(new char[] { '[', ']');\n\n    // this will give me the category for each item\n    FieldItem fi = new FieldItem { Category = category }; // more items will be added\n\n    if (!dict.Keys.Contains(category))\n       dict.Add(category, new List<FieldItem>());\n\n    dict[category].Add(fi);   \n}	0
12262505	12262387	String encoding with a JSON flow got by web request C#	WebClient webC = new WebClient();\nwebC.Encoding = Encoding.UTF8;\nstring jsonStr = webC.DownloadString("http://www.express-board.fr/api/jobs");	0
1324140	1324061	Stack overflow exception thrown from overridden property from abstract base class	public abstract class MyBaseClass\n{\n    protected string _status;\n    public virtual string Status\n    {\n        get { return _status; }\n        set { _status = value; } \n    }\n}\n\npublic class MySpecificClass : MyBaseClass\n{\n    public override string Status\n    {\n        get\n        {\n            if(_status == "something")\n                return "some status";\n            else\n                return "some other status";\n        }\n        set\n        {\n            _status = value;\n        }\n    }\n}	0
15149319	15148740	How to close TextInputPanel	using System;\nusing System.Diagnostics;\nusing System.Windows.Forms;\n\nnamespace VirtualKeyboard\n{\n    public partial class Form1 : Form\n    {\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Open_Click(object sender, EventArgs e)\n        {\n            Process.Start(@"C:\Program Files\Common Files\microsoft shared\ink\tabtip.exe");\n        }\n\n        private void Close_Click(object sender, EventArgs e)\n        {\n            Process[] processlist = Process.GetProcesses();\n\n            foreach(Process process in processlist)\n            {\n                if (process.ProcessName == "TabTip")\n                {\n                    process.Kill();\n                    break;\n                }\n            }\n        }\n\n    }\n}	0
298379	298363	How can I make SMTP authenticated in C#	using System.Net;\nusing System.Net.Mail;\n\n\nSmtpClient smtpClient = new SmtpClient();\nNetworkCredential basicCredential = \n    new NetworkCredential("username", "password"); \nMailMessage message = new MailMessage(); \nMailAddress fromAddress = new MailAddress("from@yourdomain.com"); \n\nsmtpClient.Host = "mail.mydomain.com";\nsmtpClient.UseDefaultCredentials = false;\nsmtpClient.Credentials = basicCredential;\n\nmessage.From = fromAddress;\nmessage.Subject = "your subject";\n//Set IsBodyHtml to true means you can send HTML email.\nmessage.IsBodyHtml = true;\nmessage.Body = "<h1>your message body</h1>";\nmessage.To.Add("to@anydomain.com"); \n\ntry\n{\n    smtpClient.Send(message);\n}\ncatch(Exception ex)\n{\n    //Error, could not send the message\n    Response.Write(ex.Message);\n}	0
4163347	4163266	C#: How to check whether a instance is serializable	Type t = typeof(x) \n        for fields:\n        t.GetFields().Where(p=> !p.Attributes.HasFlag(FieldAttributes.NotSerialized));\n        for type\n        t.Attributes.HasFlag(TypeAttributes.Serializable);	0
8839581	8839395	Reusable Method to change gridview cell colour	public void SetColor(DataGridViewRow row, string columnName, int cellIndex)\n{\n    var data = (GridViewRow)row.DataItem;\n    int number = Convert.ToInt32(data[columnName]);\n    if (number > 74) return;\n\n    row.Cells[cellIndex].BackColor = Color.Red;\n}\n\nprotected void gv1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType != DataRowType.DataRow) return;\n    SetColor(e, "A", 2);\n}	0
5836123	5835885	How do I change the forecolor of a control in a .NET Grid View?	if(e.Row.RowType == DataControlRowType.DataRow)\n {\n      (e.Row.FindControl("ddlStateCode") as DropDownList).ForeColor = System.Drawing.Color.LightBlue;\n }	0
3561260	3561186	Converting Lat / long to PointClass	ISpatialReferenceFactory srFactory = new SpatialReferenceEnvironmentClass();\n\nIGeographicCoordinateSystem gcs = srFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984);\nISpatialReference sr1 = gcs;\n\nIPoint point = new PointClass() as IPoint;\npoint.PutCoords(-92.96000, 44.9227);\n\nIGeometry geometryShape;\ngeometryShape = point;\ngeometryShape.SpatialReference = sr1;\n\ngeometryShape.Project(mapControl.SpatialReference);\n\nmapControl.DrawShape(geometryShape);	0
7394222	7394078	Batch update thousads of SQL rows using c#	CREATE PROC dbo.RBARBane(@tvp dbo.MyUserDefinedTableType)\nAS\nBEGIN\n    UPDATE\n        T\n    SET\n        col1 = TVP.col1\n        -- all the columns that need updated\n    FROM\n        dbo.Table T\n        INNER JOIN\n            @tvp TVP\n            ON TVP.key1 = T.key1\nEND	0
17052371	17052117	Compile a statement only if Assembly has specific version (x86 or x64)	#if WIN64\n        return Document.IdToObject(ObjectID.ToInt64()); //returns an object\n#else\n        return Document.IdToObject(ObjectID.ToInt32()); //returns an object\n#endif	0
30694825	30694743	How I can collect similar xml tag to groups with Xml.Linq in c#?	root.Elements("elements").Select(\n    e => e.Elements("element").Average(f => (int)f.Attribute("attribute"))\n)	0
3212350	3212228	C# Learning for a Beginner : To do a project without having read big concepts	MessageBox.Show()	0
20898491	20874318	Resizing Grid in Grid.Column via Storyboard?	private void Button_Click(object sender, RoutedEventArgs e)\n    {\n        MoveGrid();\n    }\n\n    private void MoveGrid()\n    {\n        var sb = new Storyboard();\n        var animation = new DoubleAnimation()\n        {\n            To = 0,\n            From = content1.ActualWidth,\n            EnableDependentAnimation = true\n        };\n        Storyboard.SetTargetProperty(animation, "Width");\n        Storyboard.SetTarget(animation, content1);\n        sb.Children.Add(animation);\n\n        sb.Begin();\n    }	0
3604693	3604561	How to write files in c# as an administrator?	Program Files	0
13255451	13253744	Adding a logo image to a chart using Microsoft Chart Control	ImageAnnotation logo = new ImageAnnotation();\n logo.X = 75;\n logo.Y = 60; \n logo.Image = "imagePath";\n chart.Annotations.Add(logo);	0
7527705	7527536	lambda Expression as a property	class CellInfo<T>\n{\n    public string Title { get; set; }\n    public string FormatString { get; set; }\n    public Func<T, object> Selector { get; set; }\n}\n\nDictionary<string, CellInfo<Person>> dict = new Dictionary<string, CellInfo<Person>>();\n\ndict.Add("LastName", new CellInfo<Person> { Selector = p => p.LastName });\ndict.Add("Age", new CellInfo<Person> { Selector = p => p.Age });\n\nforeach (Person p in someCollection)\n{\n    foreach (var cellInfo in dict)\n    {\n        object value = cellInfo.Value.Selector(p);\n    }\n}	0
31696658	31621718	how to secure add or delete entities with breezejs	_contextProvider.BeforeSaveEntitiesDelegate = BeforeSaveEntities;\n\nprivate Dictionary<Type, List<EntityInfo>> BeforeSaveEntities(Dictionary<Type, List<EntityInfo>> arg)\n        {\n            var resultToReturn = new Dictionary<Type, List<EntityInfo>>();\n            foreach (var type in arg.Keys)\n            {\n                var entityName = type.FullName;\n                var list = arg[type];\n                if (entityName == "xyz" && list[0].EntityState!="Added")\n                {\n                    resultToReturn.Add(type, list);\n                }\n            }\n            return arg;\n        }	0
14896937	14896833	MVC how to return a view after an IF statement	public ActionResult Index(string jobType)\n{\n    return (jobType.ToLower() == "this") ?\n        RedirectToAction("CandidateResults") :\n        RedirectToAction("JobResults");\n}\n\nprivate ActionResult CandidateResults()\n{\n    var model = //logic\n    return View(model);\n}\nprivate ActionResult JobResults()\n{\n    var model = //logic\n    return View(model);\n}	0
33035587	33034896	How to get certificate from .p7b file	var certificateStore = new CmsSignedData(new FileStream("chain.p7b", FileMode.Open));\nIX509Store x509Certs = certificateStore.GetCertificates("Collection");\nArrayList a = new ArrayList(x509Certs.GetMatches(null));\nX509Certificate signerCert = (X509Certificate) a[0];\n\nvar gen = new CmsSignedDataGenerator();\ngen.AddCertificates(x509Certs);\ngen.AddSigner(_privateKey, signerCert, CmsSignedGenerator.DigestSha1);\n\nCmsProcessable msg = new CmsProcessableByteArray(Encoding.ASCII.GetBytes(FullUnsignedMessage));\n\nCmsSignedData signedData = gen.Generate(msg, true);	0
24577823	23955232	Starting a process in console	var p= new System.Diagnostics.Process();\n    p.StartInfo = new ProcessStartInfo(arguments)\n    {\n        FileName="cmd.exe",\n        Arguments = "/C"+arguments,\n        CreateNoWindow = true,\n        UseShellExecute = false,\n        RedirectStandardOutput = true,\n        RedirectStandardInput = true,\n        RedirectStandardError = true\n    };\np.Start();	0
12655795	12654864	How add ArrayList to listview1 in c#	class nac\n{\n   public decimal nr_zbor ...\n   public string airport ...\n   public string company ...\n}\n\nList<nac> nacs = new List<nac>();	0
11984785	11984709	Random number generator in c#	private static int RandomNumberEven(int min, int max)\n        {\n            Random random = new Random();\n            int ans = random.Next(min, max);\n            if (ans % 2 == 0) return ans;\n            else\n            {\n                if (ans + 1 <= max)\n                    return ans + 1;\n                else if (ans - 1 >= min)\n                    return ans - 1;\n                else return 0;\n            }\n        }\n\nprivate static int RandomNumberOdd(int min, int max)\n        {\n            Random random = new Random();\n            int ans = random.Next(min, max);\n            if (ans % 2 == 1) return ans;\n            else\n            {\n                if (ans + 1 <= max)\n                    return ans + 1;\n                else if (ans - 1 >= min)\n                    return ans - 1;\n                else return 0;\n            }\n        }	0
9672531	9672461	Trying to read an MS Office Document	msWordApp.Quit()	0
7510587	7499386	How can i use dynamic columns on Linq?	var SQL1 = (from i in ESE.viw_kisiler\n                           select i);\n\n                DataTable DT = LINQToDataTable(SQL1);\n\n                var SQL2 = (from t in DT.AsEnumerable()\n                         where t.Field<string>(ColumnName).Contains(Word)\n                         select t);	0
33536889	33536280	Append XmlElement InnerXml to XmlDocument	XmlNodeList searchResultNodes = searchResult.ChildNodes;\n                        foreach (XmlNode node in searchResultNodes)\n                        {\n                            XmlElement nodeXml = GetElement(node.OuterXml);\n                            ProcessList.DocumentElement.AppendChild(ProcessList.ImportNode(nodeXml, false));\n                        }	0
16005338	16004888	Seeing multiple arguments in C# arguments as one for folder/name containing spaces?	"C:\Program Files (x86)\MiKeSoft\PCG Tools\PcgTools.exe" debug "%1"	0
3249084	3248992	throttle parallel request to remote api	submit N jobs (where N is your max in flight)\n\nWait for a job to complete, and if queue is not empty, submit next job.	0
23425881	23425779	WebBrowser .NET Windows Forms - Cut/Hide parts from the page	webbrowser1.Document.getElementById("id1").SetAttribute("style","display:none;");	0
12611261	12605809	Accessing Cell values in Excel Row using OpenXML - Object reference not set to an instance of an object	var cellValues = from cell in row.Descendants<Cell>()\n                    select cell;\n\nforeach (var cell in cellValues)\n{\n    if(cell.DataType != null \n        && cell.DataType.HasValue \n        && cell.DataType == CellValues.SharedString\n        && int.Parse(cell.CellValue.InnerText) < sharedString.ChildElements.Count)\n    {\n        DoSomething(sharedString.ChildElements[int.Parse(cell.CellValue.InnerText)].InnerText);\n    }\n    else\n    {\n        DoSomething(cell.CellValue.InnerText);\n    }\n}	0
8943501	8943312	Changing Printer Trays During Print Job	You can try something like this you have to reference \n  System.Drawing.dll from the projects --> Reference--> Add\n\n//Namespace:  System.Drawing.Printing\n//Assembly:  System.Drawing (in System.Drawing.dll)\n\nPrintDocument printDoc = new PrintDocument();\nPaperSize oPS = new PaperSize();\noPS.RawKind = (int)PaperKind.A4;\nPaperSource oPSource = new PaperSource();\noPSource.RawKind = (int) PaperSourceKind.Upper;\n\nprintDoc.PrinterSettings = new PrinterSettings();\nprintDoc.PrinterSettings.PrinterName = sPrinterName;\nprintDoc.DefaultPageSettings.PaperSize = oPS;\nprintDoc.DefaultPageSettings.PaperSource = oPSource;\nprintDoc.PrintPage += new PrintPageEventHandler(printDoc_PrintPage);\nprintDoc.Print();\nprintDoc.Dispose();	0
23454849	23454835	How to convert Date Time string to "Date Month"[5 December] format in c#?	var date = DateTime.Now.ToString("dd MMMM", CultureInfo.InvariantCulture);	0
12596248	12596003	DotNetZip How Add Selected Files without creating folders	using (ZipFile zip = new ZipFile())\n  {\n    string[] files = Directory.GetFiles(path);\n    // filter the files for *.pdf\n    zip.AddFiles(files, "Test"); //Test Folder \n    zip.Save(path+"/test.zip"); \n  }	0
1018240	1018225	Using LINQ/Lambdas to copy a String[] into a List<String>?	List<int> list = new List<int>(arr);	0
10775179	10775156	How to remove items from ItemsCollection where Tag is something?	IList<MenuItem> itemsToRemove = Items.Cast<object>().Where(mi => mi is MenuItem && ((MenuItem) mi).Tag == "Dynamic").ToList();\nforeach (MenuItem item in itemsToRemove)\n{\n    Items.Remove(item);\n}	0
23931275	23931046	How to check whether the selected tree nodes are of same order?	public static class TreeNodeExtensions {\n    public static int Level(this TreeNode value) {\n      if (Object.ReferenceEquals(null, value))\n        throw new ArgumentNullException("value"); // <- or return 0 \n\n      int result = 0;\n\n      for (TreeNode node = value; node != null; node = node.Parent)\n        result += 1;\n\n      return result;\n    }\n  }\n\n  ... \n\n  TreeNode node1 = ...\n  TreeNode node2 = ...\n\n  if (node1.Level() != node2.Level()) {\n    ...\n  }	0
7981991	7981919	C# string manipulation Regex or substring?	string[] CCindividual = Regex.Split(CCstring, "CC[0-9]+=").Where(x => x != "").\n    Select(x => x.Trim()).ToArray<String>();	0
16768787	16768742	How read a file (JSON) from directory without storing it as a string	using (var streamReader = new StreamReader("fileName.json"))\n{\n    string json = streamReader.ReadToEnd();\n    var deserializedObject = JsonConvert.DeserializeObject<SomeClass>(json);\n}	0
29172636	29166606	Why conversion from Gridview to datatable fails?	if (e.Row.RowType == DataControlRowType.DataRow)\n        { //convert that row }	0
29542328	29542096	How can i display the latest image saved in a specific directory?	private void ImageForm_Load(object sender, EventArgs e)\n        {\n var f1 = GetLatestWritenFileFileInDirectory(new DirectoryInfo(@"C:\Users\Public\Pictures\Sample Pictures"));\n  pictureBox1.ImageLocation = f1.FullName;\n}\n\n\n     private List<FileInfo> GetLastUpdatedFileInDirectory(DirectoryInfo directoryInfo)\n        {\n            FileInfo[] files = directoryInfo.GetFiles();\n            List<FileInfo> lastUpdatedFile = new List<FileInfo>();\n            DateTime lastUpdate = DateTime.MinValue;\n            foreach (FileInfo file in files)\n            {\n                if (file.LastAccessTime > lastUpdate)\n                {\n                    lastUpdatedFile.Add(file);\n                    lastUpdate = file.LastAccessTime;\n                }\n            }\n\n            return lastUpdatedFile;\n        }	0
21090397	21090287	Web page not downloading with correct encoding for arabic	private void GetRepliesStats_Load(object sender, EventArgs e)\n        {\n            WebBrowser bro = new WebBrowser();\n            bro.Navigate("http://library.islamweb.net/hadith/RawyDetails.php?RawyID=1");\n            bro.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(BrowsingCompleted);\n\n\n        }\n\nprivate void BrowsingCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n            {\n                WebBrowser browser = sender as WebBrowser;\n\n                Stream documentStream = browser.DocumentStream;\n                StreamReader streamReader = new StreamReader(documentStream, Encoding.GetEncoding("windows-1256"));\n\n                documentStream.Position = 0L;\n                String My_Result = streamReader.ReadToEnd();\n\n\n}	0
4589017	4588825	Dynamic linq-to-sql that queries based on multiple keywords	IEnumerable<Member> searchResults = members.ToList().Where(m => keywords.Any(k => m.Summary.Contains(k)))	0
13027691	13027584	how to get the value from address bar entered by client?	string usr = Request.QueryString["usr"];	0
4683904	4683834	C# need to get data from xml to verify login	public static bool IsValidLogin(string user, string password)\n{\n    XDocument doc = XDocument.Load("Login.xml");\n\n    return doc.Descendants("id")\n              .Where(id => id.Attribute("userName").Value == user \n                     && id.Attribute("passWord").Value == password)\n              .Any();\n}	0
25288685	25288419	Comparing values of a column C# list all together	if((AxiomSubSet.Select(x => x.CC).Distinct().ToList()).Count > 1)	0
31239170	31164211	Return to page after save	var id = Session["id"];\n   Session["id"] = id;	0
5631688	5631661	Retrieve index of a List<> item based in C# using Linq	var index = List.FindIndex(x=>x.ID==50);	0
19728072	19725524	TableLayoutPanel cell border style with columnspan	panel1.Dock = DockStyle.Fill;\npanel1.Margin = new Padding(0);	0
3900535	3900398	configure ObjectDataSource from Code Behind in C#	this.ObjectDataSource1.TypeName = "NamespaceName.ClassName";\nthis.ObjectDataSource1.SelectMethod = "SelectMethodName";\nthis.ObjectDataSource1.InsertMethod = "InsertMethodName";	0
6402809	6402708	c# regex - groups and nested groups	playlists = new List()\nfor line in file\n  if line is blank\n    continue\n  if line starts with "STATICTEXT"\n    playslists.add(playlist)\n    playlist = new Playlist()\n  song = parse song //this is something that regex does good\n  playlist.add(song)	0
15346340	15345830	UPDATE Command Parameters in C# For Access 2003 Not update	cmd.Parameters.AddWithValue("@FirstName", txtFirstName.Text);\ncmd.Parameters.AddWithValue("@LastName", txtLastName.Text);\ncmd.Parameters.AddWithValue("@FamDOB", txtFamDOB.Text);\ncmd.Parameters.AddWithValue("@Medical", txtMedical.Text);\ncmd.Parameters.AddWithValue("@ID", txtFamID.Text);	0
12384925	12384865	I need to check if a string contains a certain pattern using a regular expression	\[([A-Za-z]+)?#(\d)+\]	0
11505040	11469344	Is there a way to change the icon of the PrintPreview dialog in MsChart?	private void printPreviewToolStripMenuItem_Click(object sender, EventArgs e)\n    {\n        if (PrintPreviewIcon != null)\n        {\n            PrintPreviewTimer.Enabled = true;\n        }\n\n        PlotChart.Printing.PrintPreview();\n    }\n\n    private void PrintPreviewTimer_Tick(object sender, EventArgs e)\n    {\n        foreach (Form f in Application.OpenForms)\n        {\n            if (f is PrintPreviewDialog)\n            {\n                f.Icon = PrintPreviewIcon;\n                PrintPreviewTimer.Enabled = false;\n            }\n        }\n    }	0
9915122	9897935	How can I get a python script to find the right Tortoise.exe if I have multiple Tortoise clients (Git, SVN) installed?	def gen_command_string(path, url):\n    cmd = path + 'TortoiseProc.exe /command:ignore /path:\"%s\" /closeonend:0' % url\n    return cmd\n\nSVN_PATH = 'C:/Program Files/TortoiseSVN/bin'\nHG_PATH = 'C:/Program Files/TortoiseHg/bin/'\n\ncmd = gen_command_string(SVN_PATH, 'http://google.com')\ncall(cmd)	0
26117083	26116058	How to write binary data to serial port in C#	using System.IO.Ports;\n\npublic void TestSerialPort()\n{\nSerialPort serialPort = new SerialPort("COM1", 115200, Parity.None, 8, StopBits.One);\nserialPort.Open();\nbyte[] data = new byte[] { 1, 2, 3, 4, 5 };\nserialPort.Write(data, 0, data.Length);\nserialPort.Close();\n}	0
7361053	7348745	How to custom-draw a margin in a TextBox?	class FooTextBox : TextBox\n{\n    public FooTextBox()\n    {\n        margin = new Panel();\n\n        margin.Enabled   = false;\n        margin.BackColor = Color.LightGray;\n        margin.Top       = 0;\n        margin.Height    = ClientSize.Height;\n        margin.Left      = <whatever>;\n        margin.Width     = 1;\n\n        Controls.Add(margin);\n    }\n\n    Panel margin;\n}	0
9216454	9216259	Check for duplicate value	CREATE UNIQUE INDEX uix ON PERSON(NAME, LASTNAME) WHERE ACTIVE=1;	0
10401668	10401633	Validating a Textbox field for only numeric input.	int distance;\nif (int.TryParse(txtEvDistance.Text, out distance))\n{\n    // it's a valid integer => you could use the distance variable here\n}	0
27162587	27161647	How to use HtmlElement in if statement [webbrowser/winforms] in c#	private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e) {\n        if (e.Url.Equals(webBrowser1.Url)) {\n            foreach (HtmlElement ele in webBrowser1.Document.GetElementsByTagName("img")) {\n\n                ele.AttachEventHandler("onclick", Document_Click);\n            }\n        }\n    }	0
1365584	1365467	Variable expansion with Regex .NET style	void Main() // run this in LinqPad\n{\nstring text = "I was here on {D}/{MMM}/{YYYY}.";\nstring result = Regex.Replace(text, "{[a-zA-Z]+}", ReplaceMatched);\n\nConsole.WriteLine(result);\n}\n\nprivate string ReplaceMatched(Match match)\n{\nif( match.Success )\n{\nswitch( match.Value )\n{\ncase "{D}":\nreturn DateTime.Now.Day.ToString();\ncase "{YYYY}":\nreturn DateTime.Now.Year.ToString();\ndefault:\nbreak;\n}\n}\n// note, early return for matched items.\n\nConsole.WriteLine("Warning: Unrecognized token: '" + match.Value + "'");\nreturn match.Value;\n}	0
21673532	21673110	Regex to group attributes irrespective of sequence	(data-[a-z][^=]*)=("[a-z0-9"#][^=]*")	0
9889003	9888959	Lambda to get sum and single value from same child	List<Project> projects = null;\n\n        var weeksAndHours = projects\n            .Select(p => new \n            {\n                Id = p.Id,\n                Name = p.Name,\n                Weeks = p\n                    .SubProjects.SelectMany(sp => sp.Weeks)\n                    .Where(w => w.Week >= 30 && w.Week <= 35)\n                    .GroupBy(w => w.Week)\n                    .Select(g => new { week = g.Key, hours = g.Sum( w=> w.Hours) })\n            });	0
5040517	5025491	Silverlight ItemsControl behavior: how do i get an item i click on?	(e.OriginalSource as Border).DataContext as Hour	0
1324875	1272771	Set DataFormatString on DataGridView at Runtime?	DataGridView.AutoGenerateColumns = true;\nDataGridView.DataSource = dbconnection.getDataReader();\nDataGridView.DataBind();\n\nint result;\n\nfor (int i = 0; i < DataGridView.Rows.Count; i++)\n{\n  foreach (TableCell c in DataGridView.Rows[i].Cells)\n  {\n    if (int.TryParse(c.Text, out result))\n    {\n      c.Text = String.Format("{0:n0}", result);\n    }\n  }\n}	0
6236128	6236050	Hard to explain, angle and rectangle involved	var myBrush = new LinearGradientBrush(Color.Red, Color.Black, myAngle);\nmyBrush.StartPoint = new Point(myRectangle.X, myRectangle.Y);\nmyBrush.EndPoint = new Point(myRectangle.X+myRectangle.Width, myRectangle.Y+myRectangle.height);	0
7921845	7921825	Count elements in each array of a List<Array>	var zero_counts = piks.Select(p => p.Count(c => c == 0));	0
2374359	2374351	How can I examine the inheritance hierarchy of my c# application at runtime?	var a = new A();\n\nConsole.WriteLine(a.GetType().BaseType);	0
34229931	34229491	How to get list of ViewModel from database?	var clientOffers = (from cli in dbContext.Clients\n\njoin cli_ofr in dbContext.ClientOffer\non cli.ClientId\nequals cli_ofr.ClientId\n\njoin ofr in dbContext.Offers\non cli_ofr.OfferId\nequals ofr.OfferId\n\nselect new {\nClient = new Client { Guid = cli.Guid...},\nOffer = new Offer { Guid = ofr.Guid... }\n}).toList();	0
15583677	15578688	Access datatemplate element in a listbox?	Image tappedImage = new Image();\n    tappedImage = e.OriginalSource as Image;\n    textbox.Text = tappedImage.DataContext.ToString();	0
9732856	9732838	Refresh after postback causes the same data to be sent again	public void AddEmailToDB(string email)\n{\n    // first find out if the email already exists in the database\n    bool isDuplicate = ...; \n    // if it does, simply return and do nothing\n    if(isDuplicate) return; \n\n    // if control reaches here then the email is not\n    // a duplicate and you can do your normal processing\n}	0
11791982	11791942	multiple sentences in a Lambda expression	AddNumber method = r => \n{\n    Console.WriteLine(r + r);\n    Console.Read();\n};	0
11744355	11744264	C# How to format a double to one decimal place without rounding	result=string.Format("{0:0.0}",Math.Truncate(value*10)/10);	0
23887782	23887471	How to send email in asp.net	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
9653281	9653201	Directory.GetFiles: Show only files starting with a numeric value	var files = Directory.GetFiles(@"c:\mydir", "*.pdf")\n                     .Where(file => Regex.IsMatch(Path.GetFileName(file), "^[0-9]+"));\n                     //.ToArray() <-add if you want a string array instead of IEnumerable	0
21783291	21783077	How can I retrieve a cell containing a button?	TableCell tblCell = (TableCell)button.Parent;	0
9342484	9342430	Formatting LINQ Query Result Set	private object RefineResults(ResultList<Result> results)\n{           \n  // results has three properties: Summary, QueryDuration, and List\n  var refined = results.Select(x => new\n  {\n    x.ID, x.FirstName, x.LastName\n  });\n\n  return new { Results = refined, Summary = results.Summary, QueryDuration = results.QueryDuration };\n}	0
1105345	1105146	Serialize XmlDocument & send via HTTPWebRequest	use XmlDocument.OuterXml to get the XmlDocument as a string. ie:\n\nXmlDocument doc1 = new XmlDocument();\ndoc.LoadXml("Some XML");\nXmlDocument doc2 = new XmlDocument();\ndoc2.LoadXml("Some other XML");\nStringBuilder sb = new StringBuilder();\nsb.Append(doc1.OuterXml);\nsb.Append(doc2.OuterXml);	0
20743534	20741947	ZipStorer - Zip Text in MemoryStream, Transmit through httpResponse, unable open as Zip File	string text = GetLongText();\nbyte[] ba = Encoding.UTF8.GetBytes(text);\nusing (MemoryStream ms = new MemoryStream())\n{\n    using (ZipStorer zip = ZipStorer.Create(ms, "My Zip"))\n    {\n        zip.AddStream(ZipStorer.Compression.Deflate, "text.txt", new MemoryStream(ba), DateTime.Now, "My Text");\n    }\n    Response.AppendHeader("content-disposition", "attachment; filename=MyZip.zip");\n    Response.ContentType = "application/zip";\n    Response.BinaryWrite(ms.ToArray());\n    Response.End();\n}\n}	0
22401761	22401021	Load report failed in Crystal Report	doc.Load(AppDomain.CurrentDomain.BaseDirectory + "CrystalReport1.rpt");	0
25184383	25184281	Adding an Entity Framework connection string as a variable in Application Settings	"data source=localhost\sqlexpress; initial catalog=Halloween; integrated security=True;MultipleActiveResultSets=True;"	0
7094990	7094907	How to resolve a relative Url in a WCF service?	System.Web.Hosting.HostingEnvironment.MapPath("~/images")	0
4850146	4850102	How can I check a List collection for an object that has a particular property?	return myList.Any(item => item.InstanceName == "Searched name");	0
15387950	15387838	Creating a Simple Random Number in .NET	var integer = rnd1.Next((int)numericUpDown_RandomMin.Value, (int)numericUpDown_RandomMax.Value);	0
13845055	13844923	Get Child value in LINQ to Entity	decimal index = SeriesList.Select(i => i.Childs.Where(j => j.key == "aa"))\n    .FirstOrDefault()\n    .FirstOrDefault().Value;	0
4860092	4858650	C# - Programatically click a ListView Column	ColumnClickEventArgs args = new ColumnClickEventArgs(0);\n        listView1_ColumnClick(this, args);	0
10790133	10790074	Any parser generators that generate table-driven LL parsers?	LHS = RHS1 RHS2 ... RHSn ;	0
29545299	29538999	Convert from IBuffer to const unsigned char in C++ (WinRT)	IUnknown* pUnk = reinterpret_cast<IUnknown*>(buff);\nIBufferByteAccess* pBufferByteAccess = nullptr;\nHRESULT hr = pUnk->QueryInterface(IID_PPV_ARGS(pBufferByteAccess);\nbyte *pbytes = nullptr;\nhr = pBufferByteAccess->Buffer(&pbytes);	0
17513389	17513083	How to combine rows in Database if the repeat checking on two columns	DataTable _newTable = new DataTable();\n\nforeach(DataRow _row in _dataTable) {\n\n}	0
26132898	26125808	Register types from Assembly in Windsor Castle with 'where' predicate	.If(t => t.Name.EndsWith("Adapter"))	0
17160131	17160122	Generating a 4???8 digit random number	int password = random.Next(1000, 100000000);	0
30550375	30535918	How to access a Static Class Private fields to unit test its methods using Microsoft Fakes in C#	PrivateType myTypeAccessor = new PrivateType(typeof(TypeToAccess));\nmyTypeAccessor.SetStaticFieldOrProperty("bNoError", false);	0
34530774	34528246	Parse boolean XML result	var xml = new StreamReader("xmlPath");\nvar t = new XmlSerializer(typeof(Boolean),"http://schemas.microsoft.com/2003/10/Serialization/");\nvar o = t.Deserialize(xml); // true	0
17451405	17430233	How to tell which delimiter string was split on	var pageText = page.PageText.Replace("Corporate Trade Payment", "\r\nCorporate Trade Payment").Replace("Preauthorized ACH Credit", "\r\nPreauthorized ACH Credit");	0
13698977	13698652	how to find out which assembly is in gac	subst z: c:\windows\assembly	0
8701393	8701345	Learning to use Interfaces effectively	public class FileLog : ILog\n{\n    public void Log(string text)\n    {\n        // write text to a file\n    }\n}\n\npublic class DatabaseLog : ILog\n{\n    public void Log(string text)\n    {\n        // write text to the database\n    }\n}\n\npublic interface ILog\n{\n    void Log(string text);\n}\n\npublic class SomeOtherClass\n{\n    private ILog _logger;\n\n    public SomeOtherClass(ILog logger)\n    {\n        // I don't know if logger is the FileLog or DatabaseLog\n        // but I don't need to know either as long as its implementing ILog\n        this._logger = logger;\n        logger.Log("Hello World!");\n    }    \n}	0
18986735	18986619	Change return value of the method with attribute	public int DoSomething() {\n    CheckValid(); // might throw an exception\n    return 1;\n}	0
16037299	16037121	What patterns are generally interesting to look at to handle validation?	public interface IValidationHandle \n     {\n       bool Validate();         \n     }\n\n      //TODOs: Separate classes\n      public class IsTrulyValidValidator:IValidationHandle;\n      public class IsValidValitor:IValidationHandle;\n      public class EntirelyFilledValidator:IValidationHandle;\n\n      class Client\n      {\n           private IValidationHandle validator=null;\n           public void SetValidationHandler(IValidationHandle validator)\n           {\n             this.validator=validator;\n           }\n            //Where You need call\n            validator.Validate();\n       }	0
22313003	22312973	Split by space or multiple spaces, a comma or comma followed by space	Regex.Split(sentence, @"(?:\s*,\s*)|\s+")	0
26739904	26739846	Reading Last Line of a text file C#	FileStream fo = new FileStream("hello.txt", FileMode.Open);\nStreamReader sr = new StreamReader(fo);	0
1564468	1564451	How to show thumbnail of pdf in listview C#.net?	Image img1 = Image.FromFile(file.FullName);	0
24198145	24075930	How to pass selected date from AJAX calendar Control into stored procedure	string AMCStartDate = Convert.ToDateTime(AMCStartDateTextBox.Text).ToShortDateString();\ncommand.Parameters.Add(new OracleParameter("p_AMCSTARTDATE", OracleDbType.Date));\ncommand.Parameters["p_AMCSTARTDATE"].Value = AMCStartDate;	0
11474716	11474683	Inserting into a table, how to insert a auto incrementing ID	INSERT INTO tblTeams (TeamName, TeamTag) VALUES(@TEAMNAME, @TEAMTAG)	0
12372600	12372439	Finding minimum precision	int precision = (int)Math.Max(0, -Math.Floor(Math.Log10(value)));	0
9370524	9370448	Add Attribute to Base Event	[Browsable(true), EditorBrowsable(EditorBrowsableState.Always)]\n    public new event EventHandler TextChanged {\n        add {\n            base.TextChanged += value;\n        }\n        remove {\n            base.TextChanged -= value;\n        }\n    }	0
17423169	17423129	How to convert JSON object to specific format	JSON.parse	0
9563288	9563061	i want to generate payperiod for each month	for (int i = 1; i <= 12; ++i)\n{\n    DateTime firstDate = new DateTime(2012, i, 1, 0, 0, 0);\n    int daysInMonth = DateTime.DaysInMonth(2012, i);\n    DateTime endDate = new DateTime(2012, i, daysInMonth-1, 23, 59, 59);\n    DateTime TransactionDate = new DateTime(2012, i, daysInMonth, 0, 0, 0);\n    Console.WriteLine(firstDate.ToString() + \n                "," + endDate.ToString() + \n                "," + TransactionDate.ToString());\n }	0
15683442	15683378	Download and Concatenate multiple files from database	StreamWriter Writer = new StreamWriter("Filename");\n    string SQL = "select Item from Table where ID in (1, 2, 3)";\n    SqlCommand Command = new SqlCommand(SQL, Con);\n    SqlDataReader Reader = Command.ExecuteReader();\n    while (Reader.Read())\n        Writer.WriteLine(Reader["Item"].ToString());\n    Reader.Close();\n    Writer.Close();	0
19914246	19914187	ForEach, get value of next property	//Count-1 to stop at the second to last item\nfor(int i = 0; i < dm.Count-1; ++i)\n{\n      mdmList.Add(new ModifiedDefectMap()\n      {                        \n           StartingPoint = dm[i].Start,\n           Length =  dm[i+1].Start - dm[i].Start\n      });\n}	0
10348708	10348601	Windows Phone drawing ellipses	Random r = new Random();\n\nfor (int i = 0; i < 40; i++)\n        {\n            {\n                {\n                    int distance = r.Next(0, 10000);\n                    var rv = r.Next(0, 359);\n                    var x = Math.Sin(rv * Math.PI / 180) * 225;\n                    rv = r.Next(0, 359);\n                    var y = Math.Cos(rv * Math.PI / 180) * 225;\n                    Ellipse e = new Ellipse();\n                    e.Fill = new SolidColorBrush(Color.FromArgb(255, (byte)(counter * 5), (byte)(counter * 3), (byte)(counter * 1)));\n                    e.Margin = new Thickness(y, -150 + x, 0, 0);\n                    e.Width = 25;\n                    e.Height = 25;\n                    counter++;\n                    PointsGrid.Children.Add(e);\n                    //MessageBox.Show(""); // Additional line\n                }\n            }\n        }	0
15477113	15477004	Alternative to RemoveAt and Insert list items	proCraneVertices[2] =  realCraneVertices[1].Clone();	0
14813399	14811907	Want to retrive Array from database	public static Series GetIrregularTimeChartData()\n{\n    List<Series> Series = new List<Series>();\n\n    // get data from db and convert it to chart data (name, value, date)\n    var chartSeries = db.Graphs.GroupBy(x => new { x.Name })\n                      .Select(g => new\n                      {\n                          Name = g.Key,\n                          Data = g.Select(x => x.Value).ToArray(),\n                          Date = g.Select(x => x.Date).ToArray()\n                      }).ToArray();\n\n    // create 2D array => [value, date]\n    foreach (var item in chartSeries)\n    {\n        int lenght = item.Data.Count();\n        object[,] data = new object[lenght, 2];\n        for (int i = 0; i < lenght; i++)\n        {\n            data[i, 0] = item.Date[i];\n            data[i, 1] = item.Data[i];\n        }\n        Series localSeries = new Series { Name = item.Name, Data = new Data(data) };\n        Series.Add(localSeries);\n    }\n\n    return Series;\n}	0
7943544	7943481	Creating a Textured 2D Sprite using Points in XNA	vertex1= A  \nvertex2 = point(A.x, 0)  \nvertex3= B  \nvertex4 = point(B.x, 0)  \nvertex5= C  \nvertex6 = point(C.x, 0)  \nvertex7= D  \nvertex8 = point(D.x, 0)	0
7668297	7668104	When I set the Owner property of a WPF child window, am I preventing it from getting garbage collected?	// XAML in Window A\n\n<StackPanel>\n    <Button Click="Button_Click">Show Window</Button>\n    <Button Click="Button_Click_1">Garbage Collect</Button>\n</StackPanel>\n\n// Code in Window A\n private void Button_Click(object sender, RoutedEventArgs e)\n        {\n            WindowB windowB = new WindowB(this);\n            windowB.Show();\n        }\n\n        private void Button_Click_1(object sender, RoutedEventArgs e)\n        {\n            GC.Collect();\n        }\n\n    // Code in WindowB\n    public WindowB(WindowA windowA)\n    {\n        this.Owner = windowA;\n        InitializeComponent();\n    }\n\n    ~WindowB()\n    {\n        Console.WriteLine("Gone up in a puff of smoke");\n    }	0
26169550	26168830	How to Change my URL To Some Other Domain URL	protected void Application_BeginRequest(Object sender, EventArgs e)\n{\n    HttpApplication app = (HttpApplication)sender;\n\n    if (Request.RawUrl.StartsWith("http://b.com"))\n    {\n        app.Response.Redirect(Request.RawUrl.Replace("http://b.com", "http://a.com"), true);            \n        return;\n    }       \n}	0
21411388	21411227	convert list of list into array of bytes	List<List<int>> foo = new List<List<int>> { new List<int> { 1, 2, 3 }, new List<int> { 1, 2 } };\nvar flat = foo.SelectMany(x => x).ToList();	0
2508626	2508527	Dynamic select with linq-to-xml?	public string GetData(int typeOfData)\n{\n    string query = null;\n    switch (typeOfData) {\n    case 1:\n        query = "/data/car/milafe/option";\n        break;\n    case 2:\n        query = "/data/car/fuel/option";\n        break;\n    }\n\n    var results = from e in db.XPathSelectElements(query)\n        select new { ID = e.Attribute("value").Value, Name = e.Attribute("text").Value };\n}	0
12812116	12811666	Get value from the datagrid after press button/using datagrid selection changed	for(int i=0;i<DataGrid.items.count-1;i++)\n{\n     CheckBox chkBx = (CheckBox)DataGrid.items[i].Cells[3].FindControl("EmpId") ;\n     if( chkBx !=null && chkBx.Checked )\n      {\n        Response.Write(DataGrid.items[i].Cells[1].Text.ToString() );\n      }\n}	0
30248663	30247704	Find row via As Of date in a DataTable	DataTable.AsEnumerable()\n         .Where(r => r.Field<int>("Employee") == 123)\n         .OrderByDescending (r => r.Field<DateTime>("Date"))\n         .FirstOrDefault (r => r.Field<DateTime>("Date") < new DateTime(2013, 7, 8) )	0
11200815	11087904	How do I embed an Image into a RichTextBox?	foreach (Block block in rtb.Blocks)\n        {\n            if (block is Paragraph)\n            {\n                Paragraph paragraph = (Paragraph)block;\n                foreach (Inline inline in paragraph.Inlines)\n                {\n                    if (inline is InlineUIContainer)\n                    {\n                        InlineUIContainer uiContainer = (InlineUIContainer)inline;\n                        if (uiContainer.Child is Image)\n                        {\n                            Image image = (Image)uiContainer.Child;\n//Copy Image source to another repository folder and save the path.\n                        }\n                    }\n                }\n            }	0
20310788	20273874	Object properties set to null when send objects to wcf service from windows mobile 6 application	BOXTRANSACTION boxTransaction = new BOXTRANSACTION();\n                    {\n                        boxTransaction.BOXID = long.Parse(dr["BoxId"].ToString());\n                        boxTransaction.BOXIDSpecified = true;\n                        boxTransaction.TRANSACTIONDATE = DateTime.Parse(dr["TransactionDate"].ToString());\n                        boxTransaction.TRANSACTIONDATESpecified = true;	0
5930293	5909008	Unit Test for a Method that Changes the State of a private Field	PrivateObject.GetField()	0
5318627	5236939	Numericupdown force thousandsseperator to update text each keypress	private void numericUpDown1_KeyUp(object sender, KeyEventArgs e)\n        {\n            numericUpDown1.Focus();\n            //Edit:\n            numericUpDown1.Select(desiredPosition,0)\n        }	0
17822381	17821509	Loop through Dictionary to find dataType if FirstOrDefault is Null	if ( source != null )\n     {\n        var keys = ( from d in source\n                          from k in d.Keys\n                          select k ).Distinct();\n        foreach ( var key in keys)\n        {\n           //...some logic to try and find if the key.Key Value in question has any legitimate value other than null to set the DataType to      \n           var thisKey = key;\n           var valueNotNull = source.FirstOrDefault( dictionary => dictionary[thisKey] != null );\n           var colType = valueNotNull != null ? valueNotNull[thisKey].GetType() : typeof( string );\n\n\n           dt.Columns.Add( new DataColumn()\n           {\n              ColumnName = thisKey,\n              DataType = colType\n           } );\n\n        }	0
3789985	3787057	Need to activate a window	public static void forceSetForegroundWindow( IntPtr hWnd, IntPtr mainThreadId )\n{\n    IntPtr foregroundThreadID = GetWindowThreadProcessId( GetForegroundWindow(), IntPtr.Zero );\n    if ( foregroundThreadID != mainThreadId )\n    {\n        AttachThreadInput( mainThreadId, foregroundThreadID, true );\n        SetForegroundWindow( hWnd );\n        AttachThreadInput( mainThreadId, foregroundThreadID, false );\n    }\n    else\n        SetForegroundWindow( hWnd );\n}	0
3720099	3719007	How to access sharepoint resources files from Hive programmatically?	SPUtility.GetLocalizedString(...)	0
962053	962032	How do I count the number of rows returned in my SQLite reader in C#?	cmd.CommandText = "select count(id) from myTable where word = '" + word + "';";\ncmd.CommandType = CommandType.Text;\nint RowCount = 0;\n\nRowCount = Convert.ToInt32(cmd.ExecuteScalar());\n\ncmd.CommandText = "select id from myTable where word = '" + word + "';";\nSQLiteDataReader reader = cmd.ExecuteReader();\n\n//...	0
6529408	6522358	How can I get a list of keys from Json.NET?	IList<string> keys = parent.Properties().Select(p => p.Name).ToList();	0
8166606	8166563	MVC 3 2 models in a view	public class ViewModel\n{\n    public TypeOfYourModel MyModel1 { get; set; }\n    public TypeOfYourModel MyModel2 { get; set; }\n}	0
7926056	7926029	Using DateTime.AddHours from a static method does not product the desired result	public static DateTime GetCurrentDate() \n{ \n   return DateTime.Now.AddHours(6); \n}	0
24149382	24149163	Select an attribute from object in a List inside another List	//set up a collection\n\n   var xptos = new List<Xpto>() \n            { new Xpto() \n            { Sons = new List<Son> \n                { new Son() { Names = "test1" },\n                  new Son() { Names = "test2" } \n                }\n            },\n          new Xpto() \n          {\n             Sons = new List<Son> {\n             new Son() { Names = "test3" } \n           }\n           }};    \n\n //select the names\nvar names = xptos.SelectMany(r => r.Sons).Where(k => k.Names != null)\n           .Select(r => r.Names + ",") .ToList();\n\nnames.ForEach(n => Console.WriteLine(n));	0
7407739	7407702	How to get the path to the Windows fonts folder?	string fontsfolder = System.Environment.GetFolderPath(\nSystem.Environment.SpecialFolder.Fonts);	0
23377238	23377090	How to get contents of a .config file using ConfigurationManager.GetSection(columnsSectionName) without altering the sections' order?	ConfigurationManager.GetSection	0
4762798	4761003	Is there a way to customize the OpenFileDialog to select folders instead of a file?	namespace System.Runtime.CompilerServices\n{\n   [AttributeUsage(AttributeTargets.Method)]\n   public sealed class ExtensionAttribute : Attribute\n   {\n      public ExtensionAttribute() { }\n   }\n}	0
491775	491735	How do I find the install directory of a Windows Service, using C#?	String path = System.Reflection.Assembly.GetExecutingAssembly().Location;\npath = System.IO.Path.GetDirectoryName(path);\nDirectory.SetCurrentDirectory(path);	0
2200847	2200798	How can I see if a network connection changes state?	System.Net.NetworkInformation	0
19712788	19712381	c# finding active directory user by sAMAccount	using(PrincipalContext principalContext = new PrincipalContext( ContextType.Domain,\n            TargetDomain,\n            TargetDomainUserName,\n            TargetDomainPassword))\n using(var userPrincipal = UserPrincipal.FindByIdentity(principalContext, IdentityType.SamAccountName, "somaloginname"))\n{ \nuserPrincipal.SetPassword(newPassword);\n//or userPrincipal.ChangePassword\n            userPrincipal.Save();\n            }	0
18631999	18631270	Unable to get the values from the datagridview to textboxes	int i = e.RowIndex;	0
16094816	16094577	How do deal with infinitely repeating numbers as decimals?	Fraction(1, 3)	0
10581615	10495161	Slider who to store integers	_zoom = (int)Math.Round(System.Convert.ToDouble(zoom));	0
34261922	34261806	LINQ generate serial number	int serialNumber = 1;\n\nvar query = from r0w1 in dt.AsEnumerable()\n            join r0w2 in ndt.AsEnumerable()\n            on r0w1.Field<string>("ID") equals r0w2.Field<string>("CID")\n            select new string [] { serialNumber++.ToString() }\n                   .Concat(r0w2.ItemArray.Skip(1))\n                   .Concat(r0w1.ItemArray).ToArray();	0
16410964	16410904	C#, cast variable to Enum.GetUnderlyingType	var x = Convert.ChangeType(15, Enum.GetUnderlyingType(typeof(EmpType)))	0
5695117	5695056	Inserting values to a table using generic dictionary	string list<T>(IEnumerable<T> enumerable)\n {\n   List<T> list = new List<T>(enumerable);\n   return string.Join(",", list.ToArray());\n } \n\n//...\nstring sql= String.Format("INSERT INTO registrations({0}) VALUES({1})",\n                list(fields.Keys),\n                list(fields.Values));	0
8575181	8575085	How to acess a website using own asp.net page?	string url = "http://sms80.com";\nHttpWebRequest http = (HttpWebRequest)WebRequest.Create(url);\nhttp.CookieContainer = _cookieJar;\nhttp.Connection = "Keep-alive";\nhttp.Method = "POST";\nhttp.ContentType = "application/x-www-form-urlencoded";\nstring postData="username=" + username + "&password=" + password;\nbyte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);\nhttp.ContentLength = dataBytes.Length;\nStream postStream = http.GetRequestStream();\npostStream.Write(dataBytes, 0, dataBytes.Length);\npostStream.Close();\n// see if we're logged in\nHttpWebResponse httpResponse = (HttpWebResponse)http.GetResponse();\n// continue (read the response etc.)	0
3558714	3551603	C# - How can I block a method return for some interval of time?	private void Delay()\n        {\n            DelayTimer dt = new DelayTimer(1);\n            Thread thread = new Thread(new ThreadStart(dt.AddDelay));\n            thread.Start();\n            while (thread.IsAlive)\n            {\n                Application.DoEvents();\n            }\n\n        }\n\n\n\n\npublic class DelayTimer\n    {\n        private int _seconds;\n        public DelayTimer(int time)\n        {\n            _seconds = time;\n        }\n        public void AddDelay()\n        {\n           Thread.Sleep(_seconds*1000);\n        }\n    }	0
4119367	4119347	cloning a list in C#	List<MyType> lstCloned = lstOriginal.Select(i => i.Clone()).ToList();	0
11224609	11224568	How can I query an XDocument with a 'path'?	var path = "/path/to/element/I/want";\nvar route = path.Split(new []{'/'}, StringSplitOptions.RemoveEmptyEntries);\n\nXElement result = null;\nforeach (var node in route)\n{\n    if (result == null)\n    {\n        result = _xmlDocument.Element(node);    \n    }\n    else\n    {\n        result = result.Element(node);\n    }\n}\n\nreturn result;	0
20523021	20522782	Move data from one table to another in the same Database	INSERT ... SELECT	0
28880645	28879932	How to get Listbox.selected item from Class in ASP.Net	private Person aktuellPerson;\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    ListBoxPersoner.DataSource = Databasfunktioner.getPersoner();\n    ListBoxPersoner.DataValueField="PersonID";\n    ListBoxPersoner.DataTextField="Fornamn";\n    ListBoxPersoner.DataBind();\n}\n\n    protected void ListBoxPersoner_SelectedIndexChanged(object sender, EventArgs )\n   {\n       var temItem= sender as DropDownList;  // if you are talking about DropDownList\n        TextBoxFornamn.Text = temItem.SelectedItem.Text;\n    }	0
5460385	5459813	convert Html to doc in c# and return it as binary	byte[] pdfFile = System.IO.File.ReadAllBytes((string)saveto);	0
17713731	5947409	How to get HTML form data opened in Webkit.Net	String test1 = webKitBrowser1.StringByEvaluatingJavaScriptFromString("document.getElementById('email').value");	0
8012597	8012558	C# default value in constructor same as two constructors for serialization	public MyClass(string description = null) { .... }	0
11619366	11619176	How to change the font-size in PdfPTable?	Font fontH1 = new Font(Currier, 16, Font.NORMAL);\n\nPdfPTable table = new PdfPTable(1);\n\ntable.AddCell(new PdfPCell(new Phrase(yourDatabaseValue,fontH1)));	0
1061147	1061016	SharpSVN read ALL filenames	bool gotList;\n        List<string> files = new List<string>();\n\n        using (SvnClient client = new SvnClient())\n        {\n            Collection<SvnListEventArgs> list;\n\n            gotList = client.GetList(projectPath, out list);\n\n            if (gotList)\n            {\n                foreach (SvnListEventArgs item in list)\n                {\n                    files.Add(item.Path);\n                }\n            }\n        }	0
17821665	17655485	Obtain real name of photo in windows phone 8	using Microsoft.Xna.Framework.Media.PhoneExtensions;\n\nMediaLibrary m = new MediaLibrary();        \nfor (int j = 0; j < m.Pictures.Count; j++)\n{\n  var r = m.Pictures[j];\n  MessageBox.Show(MediaLibraryExtensions.GetPath(r));\n}	0
9588262	9588099	Can MonoTouch.Dialog be used with cascading data sources?	[TestFixture]	0
31055501	31055426	Use Operator from array in IF statement	if (operator1.equals("<"))\n    IsActive = value < jjj\n// etc.	0
26551824	26551447	WPF MVVM deselect textbox on Enter key press	public partial class CustomTextBox : TextBox\n{\n    public CustomTextBox()\n    {\n        InitializeComponent();\n    }\n\n    protected override void OnKeyDown(KeyEventArgs e)\n    {\n        base.OnKeyDown(e);\n        if(e.Key == Key.Return)\n        Keyboard.ClearFocus();\n    }\n}	0
25022592	25022378	Linq Select that will generate tied scores for similar values	.Select((v,i) => new { Name = v.Name, \n                         Score = v.Score, \n                         Position = \n                            players.Count(p => p.Score > v.Score) + 1\n                       }\n         );	0
11311498	11310530	How to shutdown java application correctly from C# one	System.exit()	0
2882949	2882618	In iTextSharp, can we set the vertical position of the pdfwriter?	cb.MoveTo(0f, 225f);\ncb.SetLineDash(8, 4, 0);\ncb.LineTo(doc.PageSize.Width, 225f);\ncb.Stroke();\n\nvar pos = writer.GetVerticalPosition(false);\n\nvar p = new Paragraph("test", _myFont) { SpacingBefore = pos - 225f };\ndoc.add(p);	0
28356055	28288012	Transform SQL Server text from French to Arabic	String charabia = "???????? ???????? ?????????? ????????????" ;\ntry {\n     String utf8String = new String(charabia.getBytes(), "UTF-8");\n} catch (UnsupportedEncodingException e) {\n}	0
11793175	11778013	How to get a paragraphs number in a word document with C#?	object misValue = System.Reflection.Missing.Value;\n    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();\n    object docPth = @"c:\tmp\aDoc.doc";\n    Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref docPth, ref misValue, ref misValue,\n        ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue,\n        ref misValue, ref misValue, ref misValue, ref misValue, ref misValue, ref misValue);\n    wordApp.Visible = true;\n    foreach (Microsoft.Office.Interop.Word.Paragraph aPar in aDoc.Paragraphs)\n    {\n        Microsoft.Office.Interop.Word.Range parRng = aPar.Range;\n        string sText = parRng.Text;\n        string sList = parRng.ListFormat.ListString;\n        int nLevel = parRng.ListFormat.ListLevelNumber;\n        MessageBox.Show("Text = " + sText + " - List = " + sList + " - Level " + nLevel.ToString());\n    }	0
6892663	6892609	Problem with Image in DataGridView	dataGridView1.CellFormatting += dataGridView1_CellFormatting;\n\nvoid dataGridView1_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n{            \n    if (dataGridView1.Columns[e.ColumnIndex].Name == "ImageColumnName")\n    {\n        if (collection[e.RowIndex].Result)\n        {\n            e.Value = (System.Drawing.Image)Properties.Resources.Check;\n        }\n        else\n        {\n            e.Value = (System.Drawing.Image)Properties.Resources.Cancel;\n        }\n    }\n}	0
29375662	29375523	How to show values for custom property during design-time?	public partial class UserControl1 : UserControl\n{\n    public UserControl1()\n    {\n        InitializeComponent();\n    }\n\n\n    public Planets Planet\n    {\n        get { return (Planets)GetValue(PlanetProperty); }\n        set { SetValue(PlanetProperty, value); }\n    }\n\n\n    public static readonly DependencyProperty PlanetProperty =\n        DependencyProperty.Register("Planet", typeof(Planets), typeof(UserControl1), new UIPropertyMetadata(Planets.Mercury));\n\n\n}\n\npublic enum Planets\n{ \n    Mercury, \n    Venus, \n    Earth,\n    Mars\n\n}	0
6611632	6611605	get full path of application directory	bitmap.Save(System.IO.Path.Combine(Server.MapPath("~/RELATIVE PATH OF YOUR APPLICATION"), imageName + ".png"));	0
2797665	2797647	Separate string by tab characters	string s = "123\t456\t789";\nstring[] split = s.Split('\t');	0
11740776	11740164	How to extract or access stream to specific file in gzip using SharpZipLib?	using ( FileStream inputStream = File.OpenRead ( aPackage ) )\n{\n    using ( GzipInputStream gzStream = new GzipInputStream ( inputStream ) )\n    {\n        using ( TarInputStream tarStream = new TarInputStream ( gzStream ) )\n        {\n            TarEntry entry = tarStream.GetNextEntry();\n            while ( entry != null )\n            {\n                if ( entry == theOneIWant )\n                {\n                    tarStream.CopyEntryContents (outputStream );\n                    break;\n                }\n                entry = tarStream.GetNextEntry();\n            }\n        }\n    }\n}	0
27967447	27967304	Getting keyvaluepair values dynamically	int val = 0;\nif(Conditions.A)\n    val = a.Value.ValueX;\nelse if(Conditions.B)\n    val = a.Value.ValueY;\n\n// Your code block here using "val".	0
23848663	23848629	How can I serialize an object as Json adding as root the name of the object class in a desktop C# app?	var userObj = new User() { name = "John" };\nclient.PostAsJsonAsync(url, new { user = userObj });	0
4115859	3847609	Connect to XMPP server using SASL ANONYMOUS in c#	private void XmppCon_OnSaslStart(object sender, SaslEventArgs args)\n{\n   args.Auto = false;\n   Mechanism.GetMechanismName(MechanismType.ANONYMOUS);\n}	0
15585938	15585210	Conversion failed when converting datetime from character string	SET @query\n= 'SELECT empid, name, status, ' + @cols + ' \n   FROM (SELECT empid, name, status, doortime, date + ''_'' + col AS col_names \n         FROM  (SELECT k_userid AS [empid], K_Name AS name, \n                       k_description1 as [status], K_WorktimeUp1 AS [IN], \n                       ktimeDown1 AS OUT, CONVERT(char(10), K_Date, 101) AS date \n                FROM  dbo.kq_report_analyze \n                WHERE (K_Date BETWEEN @dt AND @dt2) \n                GROUP BY K_UserID, K_Name, k_description1, K_Date, K_WorktimeUp1,\n                         K_WorktimeDown1) src  \n   UNPIVOT (doortime FOR col IN ([IN], [OUT])) unpiv) p \n   PIVOT (max(doortime) FOR col_names IN (' + @cols + ')) piv;'\n\nEXEC sp_executesql @query, N'@dt datetime, @dt2 datetime', @dt, @dt2	0
18694959	18694809	C# string parse to array	string str = "Hello, my name is Boris, [image1.jpg] i like drinking tea [img2.jpg]";\nstring[] Arr = str.Split(new char[] { '[', ']' }, StringSplitOptions.RemoveEmptyEntries);	0
1757189	1757136	Find the closest time from a list of times	DateTime fileDate, closestDate;\nArrayList theDates;\nint min = int.MaxValue;\n\nforeach (DateTime date in theDates)\n if (Math.Abs(date.Ticks- fileDate.Ticks) < min)\n {\n   min = date.Ticks- fileDate.Ticks;\n   closestDate = date;\n }	0
17270314	17270267	set AlternatingRowStyle ,HeaderStyle ,RowStyle of gridview in code behind	gv.AlternatingRowStyle.CssClass = "altrowstyle";\ngv.HeaderStyle.CssClass = "headerstyle";\ngv.RowStyle.CssClass = "rowstyle";	0
5986948	5926949	WPF MarkupExtension to Determine Assembly in which XAML is Embedded	public override object ProvideValue( IServiceProvider serviceProvider )\n{\n    var contextProvider = (IXamlSchemaContextProvider)serviceProvider.GetService( typeof( IXamlSchemaContextProvider ) );\n    var type = contextProvider.SchemaContext.GetType().Assembly.GetType( "System.Windows.Baml2006.Baml2006SchemaContext" );\n    var property = type.GetProperty( "LocalAssembly", BindingFlags.Instance | BindingFlags.NonPublic );\n    var assembly = (Assembly)property.GetValue( contextProvider, null );\n    ...\n}	0
24582242	24027188	Store all dates as BsonDocuments	ConventionRegistry.Register(\n            "Dates as utc documents",\n            new ConventionPack\n            {\n                new MemberSerializationOptionsConvention(typeof(DateTime), new DateTimeSerializationOptions(DateTimeKind.Utc, BsonType.Document)),\n            },\n            t => true);	0
14122918	14121010	Merge two Json.NET JTokens	JToken.FromObject(x.Concat(x))	0
23481493	23481462	How to create stored procedure to get value of previous column Entry in SQL Server 2008?	WITH CTE as (\n   SELECT \n     RN = ROW_NUMBER() OVER (ORDER BY EmployeeID),\n     * \n   FROM HumanResources.Employee\n )\n SELECT\n   [Previous Row].*,\n   [Current Row].*,\n   [Next Row].*\n FROM CTE [Current Row]\n LEFT JOIN CTE [Previous Row] ON \n   [Previous Row].RN = [Current Row].RN - 1\n LEFT JOIN CTE [Next Row] ON \n   [Next Row].RN = [Current Row].RN + 1\n WHERE\n       [Current Row].EmployeeID = 5	0
8317851	8317623	How to retrieve only 1 photo from Picasa using Google API with Asp.net?	PicasaEntry entry = (PicasaEntry) service.Getstring.Format("http://picasaweb.google.com/data/entry/api/user/" +\n                                                      "{0}/photoid/{1}",service.Credentials.Username,photo.GooglePhotoId	0
309429	308756	Checking an assembly for a strong name	[DllImport("mscoree.dll", CharSet=CharSet.Unicode)]\nstatic extern bool StrongNameSignatureVerificationEx(string wszFilePath, bool fForceVerification, ref bool  pfWasVerified);	0
12913342	12913098	How to check if mouse is over a button in wpf	using System.Windows.Threading;\n\nnamespace MyWPF App\n{\n/// <summary>\n/// Interaction logic for MainWindow.xaml\n/// </summary>\n\npublic partial class MainWindow : Window\n{\n\n    DateTime dt;\n    DispatcherTimer t;\n\n    public MainWindow()\n    {\n\n        InitializeComponent();\n        t = new DispatcherTimer();\n        t.Tick += new EventHandler(t_Tick);\n\n    }\n    private void button1_MouseEnter(object sender, MouseEventArgs e)\n    {\n        dt=DateTime.Now;\n        t.Interval = new TimeSpan(0, 0, 1);\n        t.IsEnabled = true;\n\n\n    }\n\n    void t_Tick(object sender, EventArgs e)\n    {\n\n        if ((DateTime.Now - dt).Seconds >= 5)\n        {\n            MessageBox.Show("Hello");// Here you can put your code which you want to execute after 5 seconds.\n        }\n\n    }\n\n    private void button1_MouseLeave(object sender, MouseEventArgs e)\n    {\n        t.IsEnabled = false;\n    }\n}\n\n}	0
19900615	19900485	how to split a string in c# using regex.split method or any normal split method to get the output as below	string[] output =\n  Regex.Matches(s, @"\([^\)]+\)+")\n  .Cast<Match>()\n  .Select(x => x.Value)\n  .ToArray();	0
5111099	5111087	Setting an integer to an enum variable	Data.Indications.IndexType indexType = (Chatham.Web.Data.Indications.IndexType)sm.FloatingComponent.IndexID.Value;	0
12599154	7922713	Set keep-alive for WebHttpBinding programmatically	private Binding CreateBinding()\n{\n    Binding binding = new WebHttpBinding();\n\n    CustomBinding customBinding = new CustomBinding(binding);\n    var transportElement = customBinding.Elements.Find<HttpTransportBindingElement>();\n    transportElement.KeepAliveEnabled = false;\n\n    return customBinding;\n}	0
13011309	13010938	Add Multiple series to a chart dynamically in asp.net	foreach(DataRow row in myDataSet.Tables["Query"].Rows)\n    {\n        // For each Row add a new series\n        string seriesName = row["SalesRep"].ToString();\n        Chart1.Series.Add(seriesName);\n        Chart1.Series[seriesName].ChartType = SeriesChartType.Line;\n        Chart1.Series[seriesName].BorderWidth = 2;\n\n        for(int colIndex = 1; colIndex < myDataSet.Tables["Query"].Columns.Count; colIndex++)\n        {\n            // For each column (column 1 and onward) add the value as a point\n            string columnName = myDataSet.Tables["Query"].Columns[colIndex].ColumnName;\n            int YVal = (int) row[columnName];\n\n            Chart1.Series[seriesName].Points.AddXY(columnName, YVal);\n        }\n    }	0
32889340	32889051	How to add disable field in ASP.NET dropdownList	ddlRolesList.Items.Insert(0, new ListItem("Select Role","NA"));	0
18647871	18645557	Entity Framework 5 poor performance	//With Auto detect changes off.\nforeach(var batch in batches)//keep batch size below 1000 items, play around with the numbers a little\n{\n    using(var ctx = new MyContext())//make sure you create a new context per batch.\n    {\n        foreach(var entity in batch){\n             ctx.Entities.Add(entity);\n        }\n        ctx.SaveChanges();\n    }\n}	0
21962914	21961086	Image size is drastically increasing after applying a simple watermark	var pngEncoder = new PngBitmapEncoder();\npngEncoder.Frames.Add(ApplyWatermark(null, null));\n\nMemoryStream stm = File.Create(image);\npngEncoder.Save(stm);\nreturn stm;	0
25561332	25561245	c# - Turning a variable for a List Item	private void box_Paid_CheckedChanged(object sender, EventArgs e)\n{\n    if (box_Paid.Checked == true)\n    {\n        Purchaser p = Purchasers[listDOF.SelectedIndex];\n        p.Paid = true;\n    }\n}	0
17109456	17109349	How can I use named range in Excel with OleDB?	using(OleDbConnection c = new OleDbConnection(con))\n{\n    c.Open();\n    string selectString = "SELECT * FROM [RANGE_NAMED]";\n    using(OleDbCommand cmd1 = new OleDbCommand(selectString))\n    {\n          cmd1.Connection = c;\n        var result = cmd1.ExecuteReader();\n        while(result.Read())\n        {\n              Console.WriteLine(result[0].ToString());\n        }\n    }\n}	0
7673086	7672936	Group List of Dictionaries by a Dictionary-key (C#)	List<decimal> monthsTotals = data\n  .GroupBy(d => d["Month"])\n  .Select(d => d.Sum( r => Convert.ToDecimal(r["Revenue"])))\n  .ToList<decimal>();	0
28984947	28970145	Method in C# to return the immediate text character of a given character	public static string GetNextLetter(string letter = null)\n{\n     if (IsStringNullOrEmpty(letter))\n         return "A";\n\n     char lastLetter = letter.Last();\n\n     if (lastLetter.ToString() == "Z")\n         return GetNextLetter(RemoveLastCharacter(letter)) + "A";\n     else\n         return RemoveLastCharacter(letter) + (char)(lastLetter + 1);\n    }	0
4803363	4794624	WMI retrieve groups that a user is member of?	private string GetGroupsForUser(string UserName)\n    {\n        ManagementObjectSearcher searcher = new ManagementObjectSearcher("select * from Win32_GroupUser where PartComponent=\"Win32_UserAccount.Domain='MyDomain',Name='" + UserName + "'\"");\n        StringBuilder strGroups = new StringBuilder();\n\n        foreach (ManagementObject mObject in searcher.Get())\n        {\n            ManagementPath path = new ManagementPath(mObject["GroupComponent"].ToString());\n\n            if (path.ClassName == "Win32_Group")\n            {\n                String[] names = path.RelativePath.Split(',');\n                strGroups.Append(names[1].Substring(names[1].IndexOf("=") + 1).Replace('"', ' ').Trim() + ", ");\n            }\n        }\n        return strGroups.ToString();\n    }	0
6834015	5984600	How to programmatically create Windows user accounts on Windows 7 or Windows Server 2008?	public UserPrincipal CreateNewUser(string sUserName, string sPassword)\n        {\n            // first check that the user doesn't exist\n            if (GetUser(sUserName) == null)\n            {\n                PrincipalContext oPrincipalContext = GetPrincipalContext();\n\n                UserPrincipal oUserPrincipal = new UserPrincipal(oPrincipalContext);\n                oUserPrincipal.Name = sUserName;\n                oUserPrincipal.SetPassword(sPassword);\n                //User Log on Name\n                //oUserPrincipal.UserPrincipalName = sUserName;\n                oUserPrincipal.Save();\n\n                return oUserPrincipal;\n            }\n\n            // if it already exists, return the old user\n            return GetUser(sUserName);\n        }\n    }	0
7464032	7463284	Get web application assembly name, regardless of current executing assembly	BuildManager.GetGlobalAsaxType().BaseType.Assembly	0
28287855	28287630	Hide part of line from an arc c#	GraphicsPath clipPath = new GraphicsPath();\nclipPath.AddEllipse(graphBoundaries);\n\ngraphics.SetClip(clipPath, CombineMode.Exclude);\n\n// draw your line\n\ngraphics.ResetClip(); // remove clip	0
6651221	6612513	Disappearing scrollbars in Monotouch UIScrollView	foreach(var subview in scrollViewer.Subviews.Skip(1))\n{\n    subview.RemoveFromSuperview();\n}\n\nscrollViewer.AddSubview(newView);\n\nscrollViewer.ContentSize = new System.Drawing.SizeF(newView.Frame.Width, newView.Frame.Height);	0
22023655	22019413	Setting default MongoDb/Bson representation for all decimals to double	void Main()\n{\n    BsonSerializer.RegisterSerializationProvider(new MyDecimalSerializer());\n    Console.WriteLine(new Test().ToJson(new JsonWriterSettings() { Indent = true }));\n}\n\nclass MyDecimalSerializer : DecimalSerializer, IBsonSerializationProvider {\n    private IBsonSerializationOptions _defaultSerializationOptions = new RepresentationSerializationOptions(BsonType.Double);\n\n    public override void Serialize(\n        BsonWriter bsonWriter,\n        Type nominalType,\n        object value,\n        IBsonSerializationOptions options) {\n        if(options == null) options = _defaultSerializationOptions;\n        base.Serialize(bsonWriter, nominalType, value, options);\n    }\n\n    public IBsonSerializer GetSerializer(Type type) {\n        return type == typeof(Decimal) ? this : null;\n    }\n}	0
8100140	8100112	Creating a window from a new thread in WPF app with no main window	window.Show	0
22101438	22100128	How to find Customer Entities logical name from Guid in Microsoft CRM	private EntityReference GetCustomerFromCase(Guid caseId)\n{\n    Entity Case = CRMCentralCRMServiceInstance.Retrieve("incident", caseId, new ColumnSet("customerid"));\n    return Case.GetAttributeValue<EntityReference>("customerid");\n}	0
14455772	14455639	How to Split an XML file into multiple XML Files based on nodes	var xDoc = XDocument.Parse(Resource1.XMLFile1); // loading source xml\nvar xmls = xDoc.Root.Elements().ToArray(); // split into elements\n\nfor(int i = 0;i< xmls.Length;i++)\n{\n    // write each element into different file\n    using (var file = File.CreateText(string.Format("xml{0}.xml", i + 1)))\n    {\n        file.Write(xmls[i].ToString());\n    }\n}	0
28125852	28125734	PowerShell Custom Object, ignore Properties at standard output	Get-Help PS1XML	0
26767398	26767282	How to grab GET parameters in ASP.NET web API?	Public Function GetValues(name As String) As IEnumerable(Of String)	0
11300236	11299781	How do I paint a pictureboxes 'centered' background image to panel?	private void panel1_Paint(object sender, PaintEventArgs e)\n{\n    var hPadding = (pictureBox1.Width - pictureBox1.BackgroundImage.Width) / 2;\n    var vPadding = (pictureBox1.Height - pictureBox1.BackgroundImage.Height) / 2;\n    var imgRect = new Rectangle(pictureBox1.Left + hPadding, pictureBox1.Top + vPadding, pictureBox1.BackgroundImage.Width, pictureBox1.BackgroundImage.Height);\n    e.Graphics.DrawImage(pictureBox1.BackgroundImage, imgRect);\n}	0
25395420	25395371	How can I determine if at least one radio button inside a groupbox is checked?	if (groupBox1.Controls.OfType<RadioButton>().Any(x => x.Checked)) {\n    // at least one radiobutton in groupbox1 is checked\n}	0
23480207	23479976	How to convert list of strings to an existing object list?	public static void WriteFile()\n{\n    Car testCar= new Car();\n    string path = "c:\temp\testCarPath.xml";\n    XmlSerializer serializer = new XmlSerializer(typeof(Car));\n    StreamWriter file = new StreamWriter(path);\n\n    serializer.Serialize(file, testCar);\n    file.Close();\n}\npublic static void ReadFile()\n{\n    Car testCar;\n    string path = "c:\temp\testCarPath.xml";\n    XmlSerializer serializer = new XmlSerializer(typeof(Car));\n    StreamReader reader = new StreamReader(path);\n\n    testCar = (Car)serializer.Deserialize(reader);\n    reader.Close();\n}	0
10218616	10218523	How to call Button OnCLick eventhandler in code behind with a value?	Button btnDelete = new Button();\n    btnDelete.Click += new EventHandler(button_Click);\n\n    protected void button_Click (object sender, EventArgs e)\n    {\n        Button button = sender as Button;\n        string buttonid = button.ID.ToString()\n        // identify which button was what row to update based on id clicked and perform necessary actions\n    }	0
2482259	2481146	Pass an array from IronRuby to C#	ls = System::Collections::Generic::List.of(String).new\nls.add("Peaches")\nls.add "Pulms"	0
16250059	16249195	location of elements in a panel wpf	var toggleButtonPosition = toggleButton.TranslatePoint(new Point(0, 0), stackPanel);\nvar textBlockPosition = textBlock.TranslatePoint(new Point(0, 0), stackPanel);	0
26324028	26323801	how to bind the Height property to a variable in c# code wpf	private void Window_Loaded(object sender, RoutedEventArgs e)\n{\n    this.H1.DataContext = new { H1 = 50 }; // here this.H1, refers to <Rectangle x:Name="H" .. \n}	0
24859910	24821637	Calling a PHP webservice from c#	public partial class TheWebServiceSubClass : ExampleService\n{\n    protected override WebRequest GetWebRequest(Uri uri)\n    {\n        HttpWebRequest webRequest = (HttpWebRequest)base.GetWebRequest(uri);\n        ExampleService client = new ExampleService();\n        string auth_id = client.authenticate_get("www.testexample.com", "e5d30c56d600a7456846164");\n        string credentials =\n            Convert.ToBase64String(Encoding.ASCII.GetBytes("www.testexample.com:e5d30c56d600a7456846164"));\n        string credentials1 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth_id+ ":"));\n        webRequest.Headers["Authorization"] = "Basic " + credentials1;\n        return webRequest;\n    }\n}	0
7621826	7561265	Recording an audio stream in C# from C++ ASIO library	delegate void ASIOCallback(IntPtr signal, int n);	0
5801155	5800967	Selecting two column values from Datagridview and displaying it in Message Box	private void button_Click(object sender, EventArgs e)\n{\n    StringBuilder message = new StringBuilder();\n    foreach (DataGridViewCell cell in this.dataGridView.SelectedCells)\n    {\n        message.AppendLine("Value = " + cell.Value);\n    }\n\n    MessageBox.Show(message.ToString());\n}	0
4059645	4059621	How to declare "global" variable in OOP project?	CarsAttack.ch[index];	0
18360709	18359818	WPF - AvalonDock - Closing Document	// ************************************************************************\n    private void DockingManager_DocumentClosing(object sender, Xceed.Wpf.AvalonDock.DocumentClosingEventArgs e)\n    {\n        e.Document.CanClose = false;\n\n        DocumentModel documentModel = e.Document.Content as DocumentModel;\n        if (documentModel != null)\n        {\n            Dispatcher.BeginInvoke(new Action(() => this.Model.DocumentItems.Remove(documentModel)), DispatcherPriority.Background);\n        }\n    }	0
1887601	1887563	get CheckedItems from checkedlistbox	int i = 0; \n    foreach (DataRowView rowView in chListBox.CheckedItems) \n    { \n        phoneNumbers[i] = rowView["ContactNumber"]; \n        i++; \n    }	0
25540633	25540503	SqlDataReader reads every other row?	string sql = @"SELECT username,password FROM users \n             WHERE username=@username and password = @password";\n\nSqlCommand userSELECTcom = new SqlCommand(sql, myConnection);\nuserSELECTcom.Parameters.AddWithValue(@username, ReceivedUsername);\nuserSELECTcom.Parameters.AddWithValue(@password, ReceivedPassword);\n\nusing(SqlDataReader reader = userSELECTcom.ExecuteReader())\n{\n   ValidLogin = reader.HasRows; \n}	0
16263636	16262243	How to check date is leading with zero?	if(stringdate[0] == '0')\n    stringdate = stringdate.Substring(1);	0
17102935	17099479	How to shrink a string and be able to find the original later	private string GetCompressedString()\n{\n    byte[] byteArray = Encoding.UTF8.GetBytes("Some long log string");\n    using (var ms = new MemoryStream())\n    {\n        using (var gz = new GZipStream(ms, CompressionMode.Compress, true))\n        {\n            ms.Write(byteArray, 0, byteArray.Length);\n        }\n\n        ms.Position = 0;\n\n        var compressedBytes = new byte[ms.Length];\n        ms.Read(compressedBytes, 0, compressedBytes.Length);\n\n        return Convert.ToBase64String(compressedBytes);\n    }\n}	0
11420005	11419843	Session expiring and auth cookie remaining	public class ControllerBase : Controller\n{\n    public ControllerBase()\n        : base()\n    {\n        this.VerifySession();  \n    }\n\n    /// <summary>\n    /// Indicates whether the session must be active and contain a valid customer.\n    /// </summary>\n    protected virtual bool RequiresActiveSession\n    {\n        get { return true; }\n    }\n\n    public void VerifySession()\n    {\n        if (this.RequiresActiveSession && Session["UserId"] == null)\n        {\n            Response.Redirect(Url.Action("LoginPage"));\n        }\n    }\n\n}\n\npublic class HomeController : ControllerBase\n{\n    protected override bool RequiresActiveSession\n    {\n        get\n        {\n            return true;\n        }\n    }\n\n    public ActionResult Index()\n    {\n        return View();\n    }\n}	0
30471112	30469889	Pastespecial Range from one workbook to another using SpreadsheetGear	srcRange.Copy(destRange, PasteType.Values, PasteOperation.None, false, false);	0
31117816	31117753	Can't open a pdf using iTextSharp	pdfReader.Close();	0
1172134	1172097	c# UK postcode splitting	string postCode = "AB111AD".Replace(" ", "");\nstring firstPart = postCode.Substring(0, postCode.Length - 3);	0
2364367	2364260	how do I handle messages asynchronously, throwing away any new messages while processing?	private IMessage _next;\n\npublic void ReceiveMessage(IMessage message)\n{\n    Interlocked.Exchange(ref _next, message);\n}\n\npublic void Process()\n{\n    IMessage next = Interlocked.Exchange(ref _next, null);\n\n    if (next != null)\n    {\n        //...\n    }\n}	0
9564965	9564938	How to close a tab from code behind?	string jScript;\n    jScript="<script>close_window();</script>";\n    ClientScript.RegisterClientScriptBlock(this.GetType(),"keyClientBlock", jScript);	0
25397589	25397450	How to get a constant's name given its value	var props = typeof(Manufacturer).GetFields(BindingFlags.Public | BindingFlags.Static);\n   var wantedProp = props.FirstOrDefault(prop => (ushort)prop.GetValue(null) == 6);	0
21386823	19593052	Live tile doesn't work after upgrading the project from WP7 to WP8	ShellTile tile = ShellTile.ActiveTiles.FirstOrDefault();\n                   if (tile != null)\n                   {\n                       FlipTileData data = new FlipTileData()\n                       {\n                           SmallBackgroundImage = new Uri("isostore:/Shared/ShellContent/" + mediumTile, UriKind.RelativeOrAbsolute),\n                           BackgroundImage = new Uri("isostore:/Shared/ShellContent/" + mediumTile, UriKind.RelativeOrAbsolute),\n                           WideBackgroundImage = new Uri("isostore:/Shared/ShellContent/" + wideTile, UriKind.RelativeOrAbsolute)\n                       };\n\n                   tile.Update(data);\n               }\nNotifyComplete();	0
1191056	1191054	How to merge a list of lists with same type of items to a single list of items?	list = listOfList.SelectMany(x => x).ToList();	0
3879730	3879687	How can I use single query to insert multiple records from Dataset into SQL Server 2005?	//First create a connection string to destination database\nstring connectionString;\nconnectionString = <EM>YourConnectionString</EM>and\n    Initial Catalog=TestSMODatabase";\n\n//Open a connection with destination database;\nusing (SqlConnection connection = \n       new SqlConnection(connectionString))\n{\n   connection.Open();\n\n   //Open bulkcopy connection.\n   using (SqlBulkCopy bulkcopy = new SqlBulkCopy(connection))\n   {\n    //Set destination table name\n    //to table previously created.\n    bulkcopy.DestinationTableName = "dbo.TestTable";\n\n    try\n    {\n       bulkcopy.WriteToServer(SourceTable); // SourceTable would come from your DataSet\n    }\n    catch (Exception ex)\n    {\n       Console.WriteLine(ex.Message);\n    }\n\n    connection.Close();\n   }\n}	0
9860408	9860387	How do I create a dynamic type List<T>	string something = "Apple";\nType type = something.GetType();\nType listType = typeof(List<>).MakeGenericType(new [] { type } );\nIList list = (IList)Activator.CreateInstance(listType);	0
5898802	5898606	Trying to return value upon Mouseup C#	protected void MyUI_MouseDown(object inSender, MouseEventArgs inArgs)\n{\n    switch(myState)\n    {\n        case CreateBox:\n            Rectangle rect = new Rectangle(inArgs.X, inArgs.Y, 0, 0);\n            break;\n    }\n} \n\nprotected void MyUI_MouseUp(object inSender, MouseEventArgs inArgs)\n{\n    rect.Width = inArgs.X - rect.X;\n    rect.Height = inArgs.Y - rect.Y;\n    // now save/draw your object\n}	0
797653	797553	How to get the time value from DateTime datatype	someDateTime.ToString("hh:mm:ss");	0
17526973	17526844	Get the values from List<EntityClass>	var functions=ListFunctions(0); // For example\nforeach(var function in functions)\n{\n  Console.WriteLine("{0} = {1}",function.ID, function.Description);\n}	0
10108085	10108027	Access variable in aspx.cs file and display in text box	TextBox_name.Text = loginEmail;	0
2520064	2520035	Inheritance of Custom Attributes on Abstract Properties	GetCustomAttributes()	0
27666404	27666341	Issue with form_load	public formCanvas()\n{\n    InitializeComponent();\n    lblUsed.Visible = false;\n    lblScore.Visible = false;\n    lblUsedLetters.Visible = false;\n    lblGuessWord.Visible = false;\n    lblUserChoice.Visible = false;\n    lblWord.Visible = true;\n    txtUserLetter.Visible = false;\n    txtUserWord.Visible = true;\n    btnSubmitWord.Visible = true;\n    btnSubmitLetter.Visible = false;\n    lblLives.Visible = false;\n    btnExit.Visible = false;\n    btnRestart.Visible = false;\n\n}	0
26300837	26287615	Posting multiple binary files in a single POST with httpclient?	var client = new HttpClient();\n\n        var stream3 = new FileStream("saved.jpg", FileMode.Open);\n        var stream2 = new FileStream("saved2.jpg", FileMode.Open);\n\n        var dic = new Dictionary<string, string>();\n        dic.Add("Test1", "This was the first test.");\n\n        var addy = "http://posttestserver.com/post.php";\n\n        using (var content = new MultipartFormDataContent())\n        {\n            content.Add(new StreamContent(stream2), "s1", "Saved1.jpg");\n            content.Add(new StreamContent(stream3), "s2", "Saved2.jpg");\n\n            var response = await client.PostAsync(addy, content);\n            response.EnsureSuccessStatusCode();\n\n            string finalresults = await response.Content.ReadAsStringAsync();\n        }	0
24194346	24125123	Get selected items in a RadGrid client-side	this._Button1.Attributes.Add("OnClick", "GetSelectedItems('" + _RadGrid1.ClientID + "');return false;");	0
5570953	5570908	RadioButtonList loses value on button Click	if(!Page.IsPostBack)	0
11616969	11616950	Exception while click on column of the grid	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e) \n{ \n    if (e.RowIndex >= 0 && e.ColumnIndex >= 0) {\n        // .. my code goes here ..\n    }\n}	0
4138226	4137552	Application uses 50% CPU after sending E-Mail	System.Net.ServicePointManager.MaxServicePointIdleTime = 1;	0
13796132	13796036	Regular Expression for word contained in a predefined set of words	var arr = ["Horse", "Pearl", "House"];\nvar string_matched="";\nfor (var i = 0; i < arr.length; i++)\n{\n    if (/se/gi.test(arr[i])) {\n\n        string_matched += ", " + arr[i];\n    }\n}	0
32941039	32893135	How to bind data from host to plugin	Application.Current.Resources.MergedDictionaries	0
15932584	15932239	Error in data reader in entity framework	db.Database.SqlQuery<IEnumerable<string>>("SELECT hospitalName FROM hospital"); //would work if all you're trying to do is get the Name\n\ndb.Database.SqlQuery<MyEntity>("SELECT * FROM hospital"); //where you define MyEntity as the same structure as the table would work\n\ndb.Database.SqlQuery<IEnumerable<Tuple<int, string>>>("SELECT * FROM hospital"); // would theoretically work although I haven't tried it.  Where the Tuple items would have to match the database types in order.  I.e. if field 1 is an int and field 2 is a string then Tuple<int,string>	0
24470943	24468025	Monotuch : Array RootElement	RootElement[] root = new RootElement[10];\n\nroot [0] = new RootElement ("caption 1");\n...\nroot [9] = new RootElement ("caption 10");	0
19999058	19998788	How to print pdf file using windows service	[RunInstaller(true)]\npublic class ServiceInstall : Installer\n{\n    public ServiceInstall()\n    {\n        ServiceInstaller serviceInstaller = new ServiceInstaller();\n        ServiceProcessInstaller serviceProcessInstaller = new ServiceProcessInstaller();\n\n        serviceProcessInstaller.Account = ServiceAccount.User;\n        serviceProcessInstaller.Username = "User";\n        serviceProcessInstaller.Password = "Password";\n\n        serviceInstaller.DisplayName = "Some Service";\n        serviceInstaller.StartType = ServiceStartMode.Automatic;\n        serviceInstaller.ServiceName = "Some Service";\n\n        this.Installers.Add(serviceProcessInstaller);\n        this.Installers.Add(serviceInstaller);\n    }\n}	0
2620489	2427144	How to clone objects in NHibernate?	Mapper.CreateMap<Transaction, Transaction>();\nvar newtransact = new Transaction();\nMapper.Map(transact, newtransact);	0
14608740	14608427	GetAsynchKeyState for Ctrl+B? How?	if (IsKeyPushedDown('B') && IskeyPushedDown(VK_CONTROL))	0
23905395	23905309	How to incrase counter value when both textbox value are equal in onClick using C#	int counter = 0;\n\n//in event\n\nif(textbox1.ToString().Equals(textbox2.ToString()))\n{\ncounter++;\n}	0
51803	51768	Print stack trace information from C#	var trace = new System.Diagnostics.StackTrace(exception);	0
24715730	24715664	Using a lambda expression to assign data to a ViewModel in a query using .Find()	var board = db.Boards.Select(b => new BoardViewModel\n    {\n        Title = b.Title\n    }).FirstOrDefault(b => b.Id == id)	0
13150802	12774248	UNITY3D: Change player control to a target model (FPS)	class NPC {\nstatic bool isBeingControlled = false;\npublic void OnUpdate() {\n    if (isBeingControlled)\n    {\n        //set camera position to NPC position (make sure you're using NPC as an instantiated class)\n        //accept key input WASD or whatever you are using and move NPC according to input.\n    }\n}	0
1287058	1287052	get names and values of a form post	foreach(string key in Request.Form){\n    Response.Write(key + "=" + Request.Form[key]);\n}	0
28479833	28479553	Load values from MySQL DB to specific column in datagrid view	string selectQuery = "select field1,field2,field3 from mytable where offerMadeBy=@param";\nMySqlConnection sqlCOnnect = new MySqlConnection(RootDBConnection.myConnection);\nMySqlCommand sqlCmd = new MySqlCommand(selectQuery,sqlCOnnect);\nsqlCmd.Parameters.AddWithValue("@param", cbox1.Text.ToString());\ntry { \n       sqlCOnnect.Open()\n       using (sqlCOnnect)\n       {\n        ....\n       }\n      }	0
5963654	5943592	Mapping a many-to-two relationship in fluent-nhibernate	public class NodeMap : ClassMap<Node>\n{\n    public NodeMap()\n    {\n        //Id and any other fields mapped in node\n\n        HasMany(x => x.Links);\n    }\n}\n\npublic class LinkMap : ClassMap<Link>\n{\n    public LinkMap()\n    {\n        //Id and any other fields mapped in node\n\n        References(x => x.StartNode);\n        References(x => x.EndNode);\n    }\n}	0
3893407	3893378	Using LINQ, how do I find an object with a given property value from a List?	if (_mQuestions.Any(q => q.QuestionID == 12)) \n{\n   Question question14 = _mQuestions.FirstOrDefault(q => q.QuestionID == 14);\n   if (question14 != null)\n       question14.QuestionAnswer = "Some Text";\n}	0
31435931	31435406	How to sort list by many criterias	class Demo\n{\n    public int Distance { get; set; }\n    public int Frequency { get; set; }\n    public override string ToString()\n    {\n        return string.Format("Distance:{0}  Frequency:{1}", this.Distance, this.Frequency);\n    }\n}\n\nList<Demo> list = new List<Demo>\n    {\n        new Demo{ Distance=3, Frequency=15},\n        new Demo{ Distance=4, Frequency=17},\n        new Demo{ Distance=5, Frequency=3},\n    };\n    int[] weight = { 30, 70 };\n    var tmp = list.OrderByDescending(x => x.Distance * 0.3 + x.Frequency * 0.7);//there just a guess\n    foreach(var q in tmp)\n    {\n        Console.WriteLine(q);\n    }	0
21316172	21315009	Importation C++ dll in C# AccessViolationException	public static extern int XIJET_GetPrinterParameter(IntPtr printerHandle,\n            Uint16 parameterIndex,\n            IntPtr pParameter, UInt16 headNumber);	0
3041270	3041130	Mapping Vectors	using System.Collections.Generic;\nnamespace Test\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            int[] vec0 = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n            int[] vec1 = { 1, 4, 2, 7, 3, 2 };\n            int[] vec2 = { 0, 0, 0, 0, 0, 0, 0, 0, 0 };\n            int[] vec3 = { 7, 2, 7, 9, 9, 6, 1, 0, 4 };\n            int[] vec4 = { 0, 0, 0, 0, 0, 0 };\n            List<int> temp = new List<int>();\n            temp.AddRange(vec0);\n            temp.AddRange(vec1);\n            temp.AddRange(vec2);\n            temp.AddRange(vec3);\n            temp.AddRange(vec4);\n            int[] mainvec = temp.ToArray();\n        }\n    }\n}	0
13671608	13671437	Adding string items to a list of type Person in C#	public class Person\n{\n    public string strFirstName;\n    ...\n}\n\npublic class Persons\n{\n    List<Person> lstPersons = new List<Person>();\n\n    public void AddPerson(string FirstName, ...)\n    {\n        Person person = new Person();\n        person.strFirstName = FirstName;\n        ...\n        lstPersons.Add(person);\n    }\n}	0
24056510	24056425	Extract the first two words from a string with C#	var WordsArray=Details.Split(); \nstring Items = WordsArray[0] + ' ' + WordsArray[1];	0
5677021	5676834	Convert String to Int and precision loss	public static int valToInt(string v)\n{     \n    return (int)(Decimal.Parse(v, new System.Globalization.CultureInfo("en-US")) * 100m);     \n}	0
9275568	9273270	How an application install and register in run of registery to run automatically with non Administrator user	string fname = Path.Combine(\n    Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicatio??????nData),\n    "your_app_name", "log.txt"); \nFile.AppendAllText(fname, "Started");	0
19313623	19313593	Create a list of int using LINQ from cell collections	var selectedRows = dGV_model.SelectedCells.Cast<DataGridViewCell>()\n                                          .Select(c=>c.RowIndex).Distinct()\n                                          .ToList();	0
4988552	4988501	Get File that was `copied to output directory` in a class library	var foo = File.ReadAllText(Server.MapPath("NewFolder1/HTMLPage1.htm"));	0
12706694	12706669	Error in in select data from table in SQL Server	sqlcomm.CommandText="select [objId] from [tablename] where cast(href as nvarchar(max))=@href"	0
29492524	29476447	Display a selected radio button from database c#	GridView grid = new GridView();\n    grid.ShowDialog(); \nif (grid.dataGridView1.CurrentRow.Cells[3].Value.ToString()=="Male")\n{male_radiobtn.Checked=true;\nfemale_radiobtn.Checked=false;}\nelse {female_radiobtn.Checked=true;\nmale_radiobtn.Checked=false;}	0
14140895	14140826	Using PsExec in a Windows Service	/accepteula	0
25330781	25324987	Detecting the duration of .wav file in resources	using NAudio.Wave;\n...\nWaveFileReader reader = new WaveFileReader(MyProject.Resource.AudioResource);\nTimeSpan span = reader.TotalTime;	0
14869431	14869375	binding a listbox	ListBox3.DataSource = ds;\nListBox3.DataTextField = "Salary";\nListBox3.DataValueField = "EmpID";\nListBox3.DataBind();	0
20764795	20764269	System.Data.SQLite.SQLiteException Attempt to write a read-only database on Windows 8	Try\n      Dim appFolder = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)\n      appFolder = Path.Combine(appFolder, "MyAppDatabaseFolder")\n      If Not Directory.Exists(appFolder) Then\n           Directory.CreateDirectory(appFolder)\n      End If\n      Dim myDB = Path.Combine(appFolder, "MY_DB.db")\n      If (Not File.Exists(myDB)) Then\n          .....\n      End If\n Catch ex As Exception\n      'Throw ex\n      Return False\n End Try	0
4516840	4516359	Performant way to store interim PDF documents in document aggregation?	pdftk folder1/file1.pdf folder1/file2.pdf folder2/file1.pdf cat output all_files.pdf	0
4479716	4479692	How to use linq to sql to select one column from row	string currentLabel = (from s2f in stream2FieldTypesTable\n                          where s2f.s2fID == item.s2fID\n                          && (s2f.s2fLabel != item.s2fLabel || s2f.s2fIsRequired != item.s2fIsRequired)\n                          select s2f.s2fLabel)\n                         .FirstOrDefault();	0
11135380	11135321	Declaring a variable of an abstract class type	private BaseClass child;\n\npublic bool DomeSomethingSpecific(int i)\n{\n        var c = {initialization to an instance - e.g. Child1(), Child2(), Child3()..};\n        if (c is Child1){\n            ((Child1)c).DomeSomethingSpecificForChild1(i);\n        }\n}	0
4247886	4246905	Print & Print Preview a Bitmap in c#	private void printDocument1_PrintPage(object sender, System.Drawing.Printing.PrintPageEventArgs e) {\n        e.Graphics.DrawImage(pictureBox1.Image, 0, 0);\n    }	0
22237591	22237391	How intelligent is Linq with IOrderedEnumerable and Where	orderedDates\n    .SkipWhile(x => x.datetime1 < afterDateTime)\n    .TakeWhile(x => x.datetime2 > beforeDateTime)	0
10537734	10537650	Draw a block of text to a certain position in the console?	void WriteLineKeepingIndent(string format, params object[] args)\n{\n    int x = Console.CursorLeft;\n    Console.WriteLine(format, args);\n    Console.CursorLeft = x;\n}	0
15147308	15118922	Naming columns in self referencing virtual properties	modelBuilder.Entity<Element>()\n    .HasMany(e => e.Parent)\n    .WithMany(e => e.Child)\n    .Map(m => {\n        m.ToTable("ElementMap"); // name of the link table\n        m.MapLeftKey("ParentID");\n        m.MapRightKey("ChildID");\n    });	0
8526628	8526427	Get selected Index in gridview by clicking on button	var rowIndex = ((GridViewRow)((Control)sender).NamingContainer).RowIndex;	0
32283577	32283443	Cannot Deserialize JSON data returning from .net web service in to C# object in an web application	protected void Button1_Click(object sender, EventArgs e)\n{\n\n    wbRfrnc.TransactionPut obj =new wbRfrnc.TransactionPut();\n    string result = obj.GetPoint(TextBox1.Text, TextBox2.Text);\n    var objGD = JsonConvert.DeserializeObject<GetData[]>(result);\n    Response.Write(objGD[0].Response); \n}	0
14205667	14205645	How to 'Trim' a multi line string?	string trimmedByLine = string.Join(\n                             "\n", \n                             temp2.Split('\n').Select(s => s.Trim()));	0
2216279	2216254	Rollback for bulk copy	using (SqlTransaction transaction = destinationConnection.BeginTransaction())\n{\n    using (SqlBulkCopy bulkCopy = new SqlBulkCopy( destinationConnection, SqlBulkCopyOptions.KeepIdentity, transaction))\n    {\n        bulkCopy.BatchSize = 10;\n        bulkCopy.DestinationTableName = "dbo.BulkCopyDemoMatchingColumns";\n\n        try\n        {\n            bulkCopy.WriteToServer(reader);\n            transaction.Commit();\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n            transaction.Rollback();\n        }\n        finally\n        {\n            reader.Close();\n        }\n    }\n}	0
5991700	5991561	Writing string to XML file without formatting (C#)	xDoc.PreserveWhitespace = true;\nxDoc.Save(...);	0
2034162	2034146	how to substring from a string using c#	String value = "A|B|C";\nString secondColumn = value.split("|")[1];	0
3617942	3617867	caching of generated xml in asp.net	XDocument x = (XDocument)HttpContext.Current.Cache[ns + "SomeRandomDate"];\nif (x == null)\n{\n  x = new XDocument(new XElement(ns + "SomeRandomDate", DateTime.Now()));\n  HttpContext.Current.Cache.Insert(ns + "SomeRandomDate", x, null,\n    DateTime.Now.AddHours(12d), Cache.NoSlidingExpiration);\n}	0
20532227	20451973	Service Locator: Get all exports	// named and nameless\n[Export("TypeA", typeof(MyPlugin))]\n[Export(typeof(MyPlugin))]\n\n// named nameless, again\n[Export("TypeB", typeof(MyPlugin))]\n[Export(typeof(MyPlugin))]\n\nclass MyPlugin { }\n\n\n[TestMethod]\npublic void mef()\n{\n    var catalog = new AssemblyCatalog(this.GetType().Assembly);\n    var container = new CompositionContainer(catalog);\n\n    Assert.AreEqual(2, container.GetExportedValues<MyPlugin>().Count());\n}	0
12875664	12875286	How to save image to Isolate Storage	byte[] imageBytes;\nHttpWebRequest imageRequest = (HttpWebRequest)WebRequest.Create(imageUrl);\nWebResponse imageResponse = imageRequest.GetResponse();\n\nStream responseStream = imageResponse.GetResponseStream();\n\nusing (BinaryReader br = new BinaryReader(responseStream ))\n{\n    imageBytes = br.ReadBytes(500000);\n    br.Close();\n}\nresponseStream.Close();\nimageResponse.Close();\n\nFileStream fs = new FileStream(saveLocation, FileMode.Create);\nBinaryWriter bw = new BinaryWriter(fs);\ntry\n{\n    bw.Write(imageBytes);\n}\nfinally\n{\n    fs.Close();\n    bw.Close();\n}	0
13549049	13539294	Allow only specific letters in specific column in RadGridView	private void radGridView1_CellValidating(object sender, CellValidatingEventArgs e)\n     {\n        String[] Acceptable = new string[] {"c", "d"};\n\n        if (e.Value != null && e.ColumnIndex == 4)\n        {\n            if(e.Value != e.OldValue)\n            {\n                if (!Acceptable.Contains(e.Value))\n                {\n                    e.Cancel = true;\n                }\n            }\n        }\n    }	0
18380197	18380060	Need to increase window service timeout	ServiceBase.RequestAdditionalTime(4000); // add 4 seconds	0
454357	454053	SQL Retrieve historical sensor values at specific date times	DECLARE\n    @start_date    DATETIME,\n    @end_date      DATETIME,\n    @chosen_time   DATETIME\nSELECT\n    @start_date    = '2009 Jan 05 00:00',\n    @end_date      = '2009 Jan 12 00:00',\n    @chosen_time   = '1900 Jan 01 17:30'   -- '1900 Jan 01' is day 0\n\nSELECT\n    <whatever>\nFROM\n    WideHistory  \nWHERE\n        [WideHistory].DateTime >= @start_date\n    AND [WideHistory].DateTime <  @end_date\n    AND DATEADD(DAY, DATEDIFF(MINUTE, 0, [WideHistory].DateTime), 0) = @chosen_time	0
2869889	2869840	Is there a way to specify the local port to used in tcpClient?	IPAddress ipAddress = Dns.GetHostEntry(Dns.GetHostName()).AddressList[0];\nIPEndPoint ipLocalEndPoint = new IPEndPoint(ipAddress, clientPort);\nTcpClient clientSocket = new TcpClient(ipLocalEndPoint);\nclientSocket.Connect(remoteHost, remotePort);	0
3500157	3498910	create polygon filled up with dots	// Create a DrawingBrush and use it to\n// paint the rectangle.\nDrawingBrush myBrush = new DrawingBrush();\n\nGeometryDrawing backgroundSquare =\n    new GeometryDrawing(\n        Brushes.Yellow,\n        null,\n        new RectangleGeometry(new Rect(0, 0, 100, 100)));\n\nGeometryGroup aGeometryGroup = new GeometryGroup();\naGeometryGroup.Children.Add(new EllipseGeometry(new Rect(0, 0, 20, 20)));\n\nSolidColorBrush checkerBrush = new SolidColorBrush(Colors.Black);\n\nGeometryDrawing checkers = new GeometryDrawing(checkerBrush, null, aGeometryGroup);\n\nDrawingGroup checkersDrawingGroup = new DrawingGroup();\ncheckersDrawingGroup.Children.Add(backgroundSquare);\ncheckersDrawingGroup.Children.Add(checkers);\n\nmyBrush.Drawing = checkersDrawingGroup;\nmyBrush.Viewport = new Rect(0, 0, 0.05, 0.05);\nmyBrush.TileMode = TileMode.Tile;   \n\nyellowPolygon.Fill = myBrush;	0
5541245	5541214	Using null-coalescing with a property or call method	object obj = collection["NoRepeate"];\nstring str = obj == null ? null : obj.ToString();	0
787952	787857	Multiple WebRequest in same session	void SaveUrl(string sourceURL, string savepath) {\n        CookieContainer cookies = new CookieContainer();\n        HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(sourceURL);\n        webRequest.CookieContainer = cookies;\n\n        HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();\n        StreamReader responseReader = new StreamReader(response.GetResponseStream());\n\n        string sResponseHTML = responseReader.ReadToEnd();\n        using (StreamWriter sw = new StreamWriter(savepath, false)) {\n            sw.Write(sResponseHTML);\n        }\n\n        string[] ImageUrl = GetImgLinks(sResponseHTML);\n        foreach (string imagelink in ImageUrl) {\n            HttpWebRequest imgRequest = (HttpWebRequest)WebRequest.Create(imagelink);\n            imgRequest.CookieContainer = cookies;\n            HttpWebResponse imgresponse = (HttpWebResponse)imgRequest.GetResponse();\n            //Code to save image\n        }\n    }	0
23557205	21988828	WinSpool OpenPrinter Access Denied	IIS_APPPOOL\mysite	0
924704	922564	Trying to open up PDF after creating it with iTextSharp, but can't get it to work?	private void respondWithFile(string filePath, string remoteFileName) \n{\n    if (!File.Exists(filePath))\n        throw new FileNotFoundException(\n              string.Format("Final PDF file '{0}' was not found on disk.", \n                             filePath));\n    var fi = new FileInfo(filePath);\n    Response.Clear();\n    Response.AddHeader("Content-Disposition", \n                  String.Format("attachment; filename=\"{0}\"", \n                                 remoteFileName));\n    Response.AddHeader("Content-Length", fi.Length.ToString());\n    Response.ContentType = "application/octet-stream";\n    Response.WriteFile(fi.FullName);\n    Response.End();\n}	0
23946973	23946067	Pass Checkbox text data into another checkbox on a seperate activity page in Xamarin C# Android?	button.Click += (sender, args) =>\n            {\n                var intent = new Intent(this, typeof(Results));\n                intent.PutExtra("cbs", new[] { cb1.Checked, cb2.Checked, cb3.Checked, cb4.Checked });\n                intent.PutExtra("texts", new[] { cb1.Text, cb2.Text, cb3.Text, cb4.Text });\n                this.StartActivity(intent);\n            };\n    }\n}\n\n[Activity(Label = "Results", MainLauncher = false, Icon = "@drawable/icon")]\npublic class Results : Activity\n{\n    protected override void OnCreate(Bundle bundle)\n    {\n        base.OnCreate(bundle);\n\n        var cbs = this.Intent.Extras.GetBooleanArray("cbs");\n        var texts = this.Intent.Extras.GetStringArray("texts");\n\n        foreach (var cb in cbs)\n        {\n            System.Diagnostics.Debug.WriteLine(cb);\n        }\n\n        foreach (var text in texts)\n        {\n            System.Diagnostics.Debug.WriteLine(text);\n        }\n\n    }\n}	0
19680495	19680396	C# custom time format	string _time_One = "08:30" ;\nstring _time_Two = "08:35" ;\n\nTimeSpan ts = DateTime.Parse(_time_One) - DateTime.Parse(_time_Two);\nMessageBox.Show(String.Format("Time: {0:00}:{1:00}", ts.Hours, ts.Minutes));	0
6144284	6144265	Append certain number of characters from a string to another string	string a = "foo";\nstring b = "bar";\n\na = a + b.Substring(0, 2); // a is now "fooba";	0
11773367	11773314	Get week from selected monthcalendar-date	public int WeekNumber(DateTime date)\n{\n    CultureInfo ciCurr = CultureInfo.CurrentCulture;\n    int weekNum = ciCurr.Calendar.GetWeekOfYear(date,\n                                          CalendarWeekRule.FirstFourDayWeek,\n                                          DayOfWeek.Monday);\n    return weekNum;\n}	0
2002104	2002093	Extension Methods on both IList and IEnumerable with the same name?	public static string Foo<T>(this IEnumerable<T> source)\n{\n    var list = source as IList<T>;\n    if(list != null)\n    {\n        // use more efficient algorithm and return\n    }\n    // default to basic algorithm\n}	0
9120483	6459838	Remove White Space Characters From String	public string RemoveSpaceAfter(string inputString)\n    {\n        try\n        {\n\n\n            string[] Split = inputString.Split(new Char[] { ' ' });\n            //SHOW RESULT\n            for (int i = 0; i < Split.Length; i++)\n            {\n                fateh += Convert.ToString(Split[i]);\n            }\n            return fateh;\n        }\n        catch (Exception gg)\n        {\n            return fateh;\n        }\n    }	0
7407687	7407537	Find a date within a string that is before a match	string x = "<tr><td>17-05-2011&nbsp;16:28&nbsp;</td><td>DB&nbsp;</td><td>(YB)&nbsp;0&nbsp;</td><td>75%&nbsp;</td>" +\n                       "<td>&nbsp;</td><td>[10] Pending - Probable</td></tr><tr><td>15-05-2011&nbsp;22:40&nbsp;</td>" +\n                       "<td>YB&nbsp;</td><td>(YB)&nbsp;0&nbsp;</td><td>90%&nbsp;</td><td>&nbsp;</td>" +\n                       "<td>[12] Solution Confirmed</td></tr>";\n            int searchBeforeLocation = x.LastIndexOf("Solution Confirmed");\n            x = x.Substring(0, searchBeforeLocation);\n            Regex r = new Regex(@"\d{2}-\d{2}-\d{4}");\n            MatchCollection matches = r.Matches(x);\n            int matchCount = matches.Count;\n            Console.WriteLine(matches[matches.Count - 1].Value);\n            Console.Read();	0
11551767	11514640	How to store the actual underlying DB value in a combobox while displaying a more user-friendly value?	comboBoxPlatypusId.SelectedIndex = comboBoxPlatypusId.Items.IndexOf(DuckbillVals[Duckbill_PlatypusID]);\ncomboBoxPlatypusId.Tag = comboBoxPlatypusId.SelectedIndex;\n...\nprivate void comboBoxFunnyMammals_SelectedValueChanged(object sender, EventArgs e) {\n    var cb = sender as ComboBox;\n    if (cb != null)\n    {\n        int validSelection = Convert.ToInt32(cb.Tag);\n        if (cb.SelectedIndex != validSelection) {\n            cb.SelectedIndex = validSelection;\n        }\n    }\n}	0
2881782	2881743	How can I fill an objects attributes in a loop	public static TEntity CopyTo<TEntity>(this TEntity OriginalEntity, TEntity NewEntity)\n    {\n        PropertyInfo[] oProperties = OriginalEntity.GetType().GetProperties();\n\n        foreach (PropertyInfo CurrentProperty in oProperties.Where(p => p.CanWrite))\n        {\n            if (CurrentProperty.GetValue(NewEntity, null) != null)\n            {\n                CurrentProperty.SetValue(OriginalEntity, CurrentProperty.GetValue(NewEntity, null), null);\n            }\n        }\n\n        return OriginalEntity;\n    }	0
30359010	30358954	Access object property in array	CreateItem[] array = new CreateItem[1];\n\nCreateItem item = new CreateItem();\nitem.name = "Necklace";\nitem.value = 5;\narray[0] = item;\n\nConsole.WriteLine(array[0].name);	0
8265375	8265293	Error while opening a connection to MS Access 2007 file: Cannot open the MS Office Access database engine workgroup information file	createMSFile.Create("Provider=Microsoft.ACE.OLEDB.12.0;Exclusive=1;Data Source=" +\n        sfdNewFile.FileName);	0
13154718	13154459	how to Calculate google map circle radius js to C#	distance = acos(\n     cos(lat1 * (PI()/180)) *\n     cos(lon1 * (PI()/180)) *\n     cos(lat2 * (PI()/180)) *\n     cos(lon2 * (PI()/180))\n     +\n     cos(lat1 * (PI()/180)) *\n     sin(lon1 * (PI()/180)) *\n     cos(lat2 * (PI()/180)) *\n     sin(lon2 * (PI()/180))\n     +\n     sin(lat1 * (PI()/180)) *\n     sin(lat2 * (PI()/180))\n    ) * 3959	0
26795206	26795187	Creating a variable for a namespace	using SW = System.Windows;\n\nSW.MessageBox.Show("");	0
18896998	18894461	cli interface with value type as return and C# interface implementation	PointD^ GetPoint();	0
19991685	19991480	Trouble with DateTime.ParseExact	var reminderDate = DateTime.ParseExact("24/01/2013", "d/MM/yyyy", null);\n\n   MessageBox.Show(reminderDate.ToString("d/MM/yyyy"));	0
27618536	27618396	Load dynamically a ResourceDictionnary	Application.Current.Resources.MergedDictionaries\n            .Add(new ResourceDictionary\n            {\n                Source = new Uri(@"pack://application:,,,/My.Application;component/Resources/Resources.xaml")\n            });	0
18801970	18801922	Serializing a C# object with additional and different element tags	class TestShow \n{\n    public string id { get; set; }\n    public string IMDB_ID { get; set; }\n    public string Language { get; set; }\n}\n\n[XmlRoot("Data")]\nclass Data \n{\n    [XmlElement("Series")]\n    public TestShow TestShow { get; set; }\n}	0
20932481	20919924	Ravendb single or multiple indexes needed?	from p in products\nselect new\n{\n   _ = p.Titles.Select(x=>CreateField("Titles_" + x.Culture, x.Text)),\n   _+ = p.Descriptions.Select(x=>CreateField("Descriptions_" + x.Culture, x.Text)),\n}	0
8807878	8807718	OS variables being used as command line arguments	Test.exe ^%Temp^%	0
6350055	6349614	Passin Bit field parameters to stored procedure using Entity Framework 4.1	list.Add(\n   new SqlParameter("print_sql", System.Data.SqlDbType.Bit) { Value = (print_sql != null ? print_sql : DBNull.Value) }\n);	0
10722221	10722157	What is the easiest way to display a table of data?	List<x> myList = GetList();\n\nmyGrid.DataSource = myList;\nmyGrid.DataBind();	0
26366054	26362419	How to stream file from disk to client browser in .Net MVC	var length = new System.IO.FileInfo(Server.MapPath(filePath)).Length;\nResponse.BufferOutput = false;\nResponse.AddHeader("Content-Length", length.ToString());\nreturn File(Server.MapPath(filePath), System.Net.Mime.MediaTypeNames.Application.Octet, fileName);	0
2227903	2227856	Finding elements of a given type in an array in C#	public IEnumerable<T> Get<T>()\n{\n  return _vehicles.OfType<T>();\n}	0
2808403	2808384	String Manipulation with Regex	yourString = Regex.Replace(yourString, @"\bFUT\w*?\b", "");	0
3079579	3079567	C# Get Cookies from server response provided on data POST	var cookieContainer = new CookieContainer();\nWebReq.CookieContainer = cookieContainer;	0
25611182	25608177	How to SetWindowPos Z-order of a window to just under the activated window?	[DllImport("user32.dll")]\n[return: MarshalAs(UnmanagedType.Bool)]\nprivate static extern bool IsIconic(IntPtr hWnd); //returns true if window is minimized\n\nprivate List<IntPtr> windowsHandles = new List<IntPtr>();\n//fill list with window handles\n\nfor (i = 0; i < windowsHandles.Count; i++)\n{\n    if (windowsHandles[i] != browserHandle && windowsHandles[i] != this.Handle && !IsIconic(windowsHandles[i]))\n    { \n        SetWindowPos(windowsHandles[i], HWND_BOTTOM, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE);\n    }\n}	0
596012	596003	Making a Non-nullable value type nullable	Nullable<T>	0
5955982	5955955	how do i return a count of match items	int count = 0;\nmySortedlist.FindAll(delegate(myclass tmp){ return (tmp.ID == 123 && ++count <= 10);});	0
6379150	4786302	Getting an error with a web browser control in a WinForms Application	webBrowser1.ScriptErrorsSuppressed = true;	0
12305774	12305742	Rx IObservable - return first IObservable stream to get a value	IObservable<T> fastest = slowObservables.Amb();	0
34540899	34504637	how to sort a datatable except for a one row value	DataTable dt = bLStatus.GetStatusDetail();\n            if (dt != null && dt.Rows.Count > 0)\n            {\n                dt.DefaultView.Sort = "Description ASC";\n                DataTable dt2 = dt.DefaultView.ToTable();\n\n                DataRow row1 = dt2.NewRow();\n                row1["Description"] = "All";\n                dt2.Rows.InsertAt(row1, 0);\n\n                cmbCurrentStatus.DataSource = dt2;\n                cmbCurrentStatus.ValueMember = "Description";\n                cmbCurrentStatus.DisplayMember = "Description";\n\n            }	0
17387214	17387133	saveFileDialog How to save to user input?	if (saveFileDialog1.ShowDialog() == DialogResult.OK)\n        {\n            System.Net.WebClient web = new WebClient();\n            web.DownloadFile(url, saveFileDialog1.FileName);\n            web.Dispose();\n        }	0
6353870	6353350	Multiple where conditions in EF	var filteredData = _repository.GetAll();\n//If your data source is IEnumerable, just add .AsQueryable() to make it IQueryable\n\nif(keyWordTextBox.Text!="")\n    filteredData=filteredData.Where(m=>m.Keyword.Contains(keyWordTextBox.Text));\n\nif(LocationDropDown.SelectedValue!="All")\n    filteredData=filteredData.Where(m=>m.Location==LocationDropDown.SelectedValue));\n\n... etc....	0
19052410	19052171	Quering a Dynamic Object List for Max and Min Values	string Data = @"[{\n    ""created_at"": ""Fri Sep 27 02:00:08 +0000 2013"",\n    ""id"": 1\n},\n{\n    ""created_at"": ""Sat Sep 28 02:00:08 +0000 2013"",\n    ""id"": 1\n}]";\nIEnumerable<dynamic> d = (dynamic)JsonConvert.DeserializeObject(Data);\nvar dates = d.Select(x => DateTime.ParseExact(x.created_at.ToString(),\n    "ddd MMM dd HH:mm:ss K yyyy", CultureInfo.InvariantCulture))\n    .Cast<DateTime>().ToList();\nvar maxDate = dates.Max();\nvar minDate = dates.Min();	0
7016966	7016925	Read a file in such a way that other processes are not prevented from modifying it	FileShare.ReadWrite | FileShare.Delete	0
7373828	7373656	Linq to XML parsing a single "status" node from the twitter API	XElement tweet = XElement.Parse(e.Result);\nvar thisTweet = new Tweet()\n{\n    created_at = tweet.Element("created_at").Value,\n    text = tweet.Element("text").Value,\n\n    //user info\n    name = tweet.Element("user").Element("name").Value,\n    profile_image_url = tweet.Element("user").Element("profile_image_url").Value,\n    screen_name = tweet.Element("user").Element("screen_name").Value,\n    user_id = tweet.Element("user").Element("id").Value\n\n};	0
20708014	20660672	How to improve performance on two thread accesing a collection of items concurrently	public class BlockingQueue<T> { \n    private Queue<Cell<T>> m_queue = new Queue<Cell<T>>(); \n    public void Enqueue(T obj) { \n        Cell<T> c = new Cell<T>(obj);\n        lock (m_queue) {\n            m_queue.Enqueue(c); \n            Monitor.Pulse(m_queue); \n        }\n    } \n    public T Dequeue() { \n        Cell<T> c; \n        lock (m_queue) { \n            while (m_queue.Count == 0) Monitor.Wait(m_queue); \n            c = m_queue.Dequeue();\n        } \n        return c.m_obj; \n    } \n}\n\nclass Cell<T> { \n    internal T m_obj; \n    internal Cell(T obj) { \n        m_obj = obj;\n    } \n}	0
3221326	3221287	Using the OpenFileDialog control in a C# application	private void LoadImageToMemory()\n        {\n            openFileDialog1.Filter = "png files (*.png)|*.png|jpg files (*.jpg)|*.jpg";\n            openFileDialog1.Multiselect = false;\n            openFileDialog1.InitialDirectory = @"C:\";\n            openFileDialog1.Title = "Select a picture to transform.";\n\n            if (openFileDialog1.ShowDialog() == DialogResult.OK)\n            {\n                txtFileName.Text = openFileDialog1.FileName;\n            }            \n        }	0
1823665	1823655	Given a C# Type, Get its Base Classes and Implemented Interfaces	Type.GetAllBaseClassesAndInterfaces	0
6947523	6947470	C#-How to use empty List<string> as optional parameter	public void Process(string param1, List<string> param2 = null) {\n    param2 = param2 ?? new List<String>();\n}	0
6191645	6191609	Can anyone help me with a question about Interfaces in C#	public partial class Student : IUniversityPerson{ ... }	0
18560134	18552750	Upload image to a server from PictureBox	using (MemoryStream m = new MemoryStream())\n{\n    m.Position = 0;\n    bmp.Save(m, ImageFormat.Png);\n    bmp.Dispose();\n    data = m.ToArray();\n    MemoryStream ms = new MemoryStream(data);\n    // Upload ms\n}	0
34296309	34296043	Getting local hour with NodaTime	var centralTime = centralTimeZone.AtLeniently(localDateTime);\nvar easternTime = centralTime.InZone(easternTimeZone);	0
21228004	21227522	How to read this message from text file?	// Reading the file\n  String text = File.ReadAllText(@"MyMessageFile.txt");\n\n  // Parsing: startIndex - index of the first '{' from the heading\n  // that is  #Msg ... 10001   \n  int startIndex = text.IndexOf('{', Regex.Match(text, @"#Msg\ *10001").Index);\n  // stop index: closing '}'\n  int stopIndex = text.IndexOf('}', startIndex);\n\n  // Message is text between '{' and '}'\n  // heading and trailing whitespaces (\n, \n, ' ')  removed\n  String message = text.Substring(startIndex + 1, stopIndex - startIndex - 1).Trim(' ', '\r', '\n');	0
15948382	15948328	C# Execute another program on button click	Process notePad = new Process();    \nnotePad.StartInfo.FileName   = "notepad.exe";\nnotePad.StartInfo.Arguments = "ProcessStart.cs"; // if you need some\nnotePad.Start();	0
29612953	29612265	count row color in datagrid	public void CountRowColor()\n    {\n        int red = 0, yellow = 0;\n\n        foreach(DataGridViewRow row in dataGridView1.Rows)\n        {\n            if (row.DefaultCellStyle.BackColor == Color.Red)\n                red++;\n            if (row.DefaultCellStyle.BackColor == Color.Yellow)\n                yellow++;\n        }\n\n        this.label14.Text = yellow.ToString();\n        this.label16.Text = red.ToString();\n    }	0
17073129	17072903	Can someone suggest a design pattern or basic architecture for an application that relies on integrating with 3rd party services	GetRequestType( database.SomeThirdParty.RequestTypeEnumValue )	0
4970551	4970231	ObjectContext.ExecuteStoreCommand, how to clear parameters between calls?	var argsDeleteWebUserXref1 = new DbParameter[] {         new SqlParameter { ParameterName = "WebUserId", Value = user.WebUserId }  \n\nvar argsDeleteWebUserXref2 = new DbParameter[] {         new SqlParameter { ParameterName = "WebUserId", Value = user.WebUserId }  \n\nrowsAffectedDeleteWebUserXref += base.context.ExecuteStoreCommand(sqlDeleteWebUserGreen, argsDeleteWebUserXref1);      \nrowsAffectedDeleteWebUserXref += base.context.ExecuteStoreCommand(sqlDeleteWebUserBlue, argsDeleteWebUserXref2);	0
26117635	25668353	How to restrict authorization to controllers in ASP.NET MVC 4 app based on 'Admin' attribute in User database table	string username = User.Identity.Name;\nbool isadmin = select admin from db where user == username;\nif(isadmin)\n{\nreturn View();\n}\nelse\n{\nreturn HttpNotFound();\n}	0
16537658	16537607	Representing data in array or collection to iterate	var v = new { Amount = 108, Message = "Hello" };\nConsole.WriteLine(v.Amount + v.Message);	0
34381143	34380912	How to add a connection string to app.config or web.config?	System.Configuration.Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);\nconfig.AppSettings.Settings.Add("Lorem", "metadata=res://*/Models.HOGC.csdl|res://*/Models.HOGC.ssdl|res://*/Models.HOGC.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=(local);initial catalog=Ipsum;user id=sa;password=Qwer0987;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient");\nconfig.Save(ConfigurationSaveMode.Modified);\nConfigurationManager.RefreshSection("appSettings");	0
13476911	13476559	Using LINQ and EF, how to remove values from database where not in list of items	//asuming your db has these fields: db.Shifts, db.OperatorShifts\n//and model is the current Operator\n\nvar existingShifts = (from os in db.OperatorShifts\n                where os.OperatorId == model.Id\n                select os).ToList();\n\nIEnumerable<Guid> newShiftIds = ?; //don't now how your selected shift ids got post back, figure it out yourself\n\nvar shiftsToRemove = existingShifts.Where(e => newShiftIds.All(id => e.Id != id)).ToList();\nvar shiftIdsToAppend = newShiftIds.Where(id => exising.All(e => e.Id != id)).ToList();\n\nforeach(var shift in shiftsToRemove)\n{\n    db.OperatorShifts.Remove(shift);\n}\n\nforeach(var shiftId in shiftIdsToAppend)\n{\n    db.OperatorShifts.Add(new OperatorShift{\n        OperatorId = model.Id,\n        ShiftId = shiftId\n    });\n}	0
14264356	14263331	Repository and Unit of Work patterns - How to save changes	public interface IRepository<T>\n{\n     T Get(int id);\n     void Add(T entity);\n     void Update(T entity);\n     void Remove(T entity);\n     void Save();\n}	0
31019562	31019521	Does string.Format add extra quotes to value	string.Format("sample {0}", "blah")	0
23438990	23400908	Tesseract OCR - Handwritten data definition	tesseract-2.00.eng.tar.gz	0
32095183	32094232	NHibernate sql query without map one column one row	var session = ... ; // standard session, with access to other mapped stuff\nvar sql = "SELECT settingCol FROM dbo.myTable WHERE ... ";\nvar result = session\n    .CreateSQLQuery(sql)\n    .UniqueResult<string>(); // or <int>	0
26554502	26554233	Databind two or more entities to a single DataSource (EF6)	public class Orders\n{\n    public int OrderID { get; set; }\n    public decimal Total { get; set; }\n    public DateTime Date { get; set; }\n\n    public virtual Clients Clients { get; set; }\n\n    public string ClientsName\n    {\n      if(Clients != null)\n      {\n         return Clients.Name\n      }\n\n      return string.Empty;\n    }\n}	0
3520038	3448297	Replacing Content Controls in OpenXML	private void DeleteSdtBlockAndKeepContent(MainDocumentPart mainDocumentPart, string sdtBlockTag)\n    {\n        List<SdtBlock> sdtList = mainDocumentPart.Document.Descendants<SdtBlock>().ToList();\n        SdtBlock sdtA = null;\n\n        foreach (SdtBlock sdt in sdtList)\n        {\n            if (sdt.SdtProperties.GetFirstChild<Tag>().Val.Value == sdtBlockTag)\n            {\n                sdtA = sdt;\n                break;\n            }\n        }\n\n\n        OpenXmlElement sdtc = sdtA.GetFirstChild<SdtContentBlock>();\n        OpenXmlElement parent = sdtA.Parent;\n\n        OpenXmlElementList elements = sdtc.ChildElements;\n\n        var mySdtc = new SdtContentBlock(sdtc.OuterXml);\n\n        foreach (OpenXmlElement elem in elements)\n        {\n\n            string text = parent.FirstChild.InnerText;\n            parent.Append((OpenXmlElement)elem.Clone());\n        }\n\n        sdtA.Remove();\n    }	0
27038810	27037552	HttpClient - how to figure out if server is down faster?	var task = Task.Run(() => { \n                var req = new HttpClient().GetAsync("http://www.google.com");\n                if (!req.Wait(10000))//wait for 10 seconds\n                    throw new TaskCanceledException(req);\n            });\ntask.Wait();	0
10313170	10312771	how to get actual height of Grid Row before rendering	//Make the framework (re)calculate the size of the element\n    _Element.Measure(new Size(Double.MaxValue, Double.MaxValue));\n    Size visualSize = _Element.DesiredSize;\n    _Element.Arrange(new Rect(new Point(0, 0), visualSize));\n    _Element.UpdateLayout();	0
1662324	1662083	How test SqlParameter for equality	Expect.Once.On(mockSqlDao).Method("ExecuteNonQuery")\n          .With("usp_Update_Comment", Has.Property("ParameterName").EqualTo("@Id") & \n                                      Has.Property("Value").EqualTo(1));	0
30091793	30090429	Saving an XML file to a specific folder	string propertyFile = @"C:\Users\myName\Desktop\ProgramFolder\assembly\settings.xml";
\n            string propertyFolder = propertyFile.Substring(0, propertyFile.LastIndexOf("\\") + 1);
\n            string newXML = propertyFolder + "newXML.xml";
\n
\n            //XmlDocument doc name of xml document in code
\n            doc.Save(newXML);???	0
27016114	27016004	C# Java issue with String to Array to String	string yourString = "this,is,a,example,string";\n        string newString = "";\n\n        string[] array = yourString.Split(',');\n\n        foreach (string s in array)\n        {\n            newString += s;\n        }\n\n        Console.WriteLine(newString);	0
20434141	20434073	Change stubbed method argument with RhinoMocks 3.6?	loanStatusUpdater\n        .Stub(x => x.TryUpdateStatus(loan))\n        .WhenCalled(call => ((Loan)call.Arguments[0]).LOAN_STATUS = "A");                         \n        .Return(true);	0
9881507	9881409	Create outlook message with attachment using vb.net	void Main()\n{\n    // Create an Outlook application.\n    Outlook._Application oApp;\n    oApp = new Outlook.Application();\n\n    // Create a new MailItem.\n    Outlook._MailItem oMsg;\n    oMsg = oApp.CreateItem(Outlook.OlItemType.olMailItem);\n    oMsg.Subject = "Send Attachment Using OOM in Visual Basic .NET";\n    oMsg.Body = "Hello World" + vbCr + vbCr;\n\n    // TODO: Replace with a valid e-mail address.\n    oMsg.To = "user@example.com";\n\n    // Add an attachment\n    // TODO: Replace with a valid attachment path.\n    string sSource = "C:\\Temp\\Hello.txt";\n    // TODO: Replace with attachment name\n    string sDisplayName = "Hello.txt";\n\n    string sBodyLen = oMsg.Body.Length;\n    Outlook.Attachments oAttachs = oMsg.Attachments;\n    Outlook.Attachment oAttach;\n    oAttach = oAttachs.Add(sSource, , sBodyLen + 1, sDisplayName);\n\n    // Send\n    oMsg.Send();\n\n    // Clean up\n    oApp = null;\n    oMsg = null;\n    oAttach = null;\n    oAttachs = null;\n}	0
13871824	13871601	c# - Hide button text when another button is clicked	public partial class Form1 : Form\n{\n    Button lastButton = null;\n    int buttoncount;\n\n    public Form1()\n    {\n        InitializeComponent();\n        button1.Tag = "Ford Mustang";\n        button2.Tag = "Ford Focus";\n        button3.Tag = "Chevy Malibu";\n        button4.Tag = "Chevy Camaro";\n        button1.Click += button_Click;\n        button2.Click += button_Click;\n        button3.Click += button_Click;\n        button4.Click += button_Click;\n        //etc...\n    }\n\n    void button_Click(object sender, EventArgs e)\n    {\n        if (lastButton != null)\n        {\n            SwitchTagWithText();\n        }\n\n        lastButton = sender as Button;\n        SwitchTagWithText();\n\n        buttoncount++;\n        label2.Text = buttoncount.ToString();\n    }\n\n    void SwitchTagWithText()\n    {\n        string text = lastButton.Text;\n        lastButton.Text = lastButton.Tag.ToString();\n        lastButton.Tag = text;\n    }\n}	0
31601674	31601439	How to retrieve the selected value of a RadioGroup	private void Save()\n    {\n        List<Element> elementList = new List<Element> ();\n        elementList = Root [1].Elements;\n        foreach (Element element in elementList) {\n            RootElement radioElement = (RootElement)element;\n            user.Title = radioElement[0].Elements[radioElement.RadioSelected].Caption;\n        }\n        user.Save ();\n    }	0
8370369	8370347	Can not convert int to string	ddlCity.Items.FindByValue(CityID.ToString()).Selected = true	0
12003079	12003033	how to get/read file name from FileUpload control?	var fileName = FileUpload1.PostedFile.FileName;	0
27945835	27945742	XmlWriter writing everything to a single line	XmlWriterSettings settings = new XmlWriterSettings();\nsettings.Indent = true;\n// other settings...\n\nXmlWriter xmlWriter = XmlWriter.Create(exportFile, settings);	0
3362276	3362260	How to make C# DataTable filter	dtData.Select("ID=1 AND ID2=3");	0
2550875	2550872	reset the data in the table of data set in c#.net	combobox1.datasource = null;\ncombobox1.items.clear();	0
5944790	5944591	Finding the amount of intersection on two lines	(outVect.X-a1.X), (outVect.Y-a1.Y)	0
18680951	18680386	How I use XDocument.Load() to get a file in the application directory	XDocument xml = XDocument.Load("Registro.xml");	0
3566737	3566659	How to find a node(or element) in XPath, when the path to that node is always different	//*[contains(text(), 'text you want to find')]	0
17535500	17534280	Recursively create accordion html from list of links in C#	HtmlNodeCollection OneHome = document.DocumentNode.SelectNodes("//div[@id='accordion1']");\n    var OneHomelinks = OneHome.Descendants("a")\n            .Select(a => a.OuterHtml)\n            .ToList();\n    var headerCount = 0;\n    foreach (string link in OneHomelinks)\n    {\n        var prevCounter = headerCount;\n        if (link.Contains('#'))\n        {\n            headerCount++;\n\n            if (headerCount != 1 && headerCount > prevCounter) {\n                Response.Write("</ul>");\n                Response.Write("</p>");\n                Response.Write("</div>");\n            }\n\n            Response.Write("<div data-role=\"collapsible\" data-collapsed=\"true\">");\n            Response.Write("<h3>" + link + "</h3>");\n            Response.Write("<p>");\n            Response.Write("<ul>");\n\n\n        }\n        else {\n            Response.Write("<li>" + link + "</li>");\n        } \n    }\n    Response.Write("</ul>");\n    Response.Write("</p>");\n    Response.Write("</div>");	0
3822272	3822164	Sorting a ListView in C# causing crashes	protected void list_Sorting(object sender, ListViewSortEventArgs e)\n{\n     ...\n     list.Sort(sortColumn, sortDirection);\n     ...\n}	0
15817243	15817053	How return List<string>[] in a web service method	public List<string>[] SomeClientBuilsenessLogicMethod()\n{\n    var serviceClient = GetServiceClientInstance(); //you might want to have single instance (single connection) of WCF service client, so I implemented it's creation as factory method here.\n\n    string[][] serviceData = serviceClient.MyMethod();\n\n    List<string>[] mutableDataList = serviceData.Select(x=>x.ToList()).ToArray();//Not the best memory usage here probably (better is a loop), but for not big data lists it's fine.\n\n    //Perform any needed operations for list changing. Again there is NO NEED to use List if you don't plan to add/remove items to/from that collection.\n\n    return mutableDataList;\n}	0
33325186	33319749	ItemsSource to property of SelectedItem of TreeView	public ObservableCollection<efcFixtureMode> Modes { get; set; }	0
12801057	12714741	Change sharepoint list item permission based on value slected in Person or Group type	SPWeb web = SPContext.Current.Web;\nSPGroup oGroup = web.Groups.GetByID   (oFieldUserValue.LookupId);   //Look up field value                                     \nSPPrincipal principal = (SPPrincipal)oGroup;\nSPRoleAssignment roleAssignment = new SPRoleAssignment(principal);                                        \npermFolder.Item.BreakRoleInheritance(true);                                        \nroleAssignment.RoleDefinitionBindings.Add(web.RoleDefinitions["Contribute"]);\npermFolder.Item.RoleAssignments.Add(roleAssignment);\npermFolder.Item.Update();\nfinalItem.Update();	0
6659049	6659036	how to calculate average rating	double avg = 0;\nfor (int i = 0; i < arr.Length; i++) // arr.Length should be the same as MaxRate\n{\n    avg += arr[i] * (i + MinRate);\n}\navg /= arr.length;	0
26681591	26681268	How to read xml string ignoring header?	private string _GetXmlWithoutHeadersAndComments(XmlDocument doc)\n{\n    string xml = null;\n\n    // Loop through the child nodes and consider all but comments and declaration\n    if (doc.HasChildNodes)\n    {\n        StringBuilder builder = new StringBuilder();\n\n        foreach (XmlNode node in doc.ChildNodes)\n            if (node.NodeType != XmlNodeType.XmlDeclaration && node.NodeType != XmlNodeType.Comment)\n                builder.Append(node.OuterXml);\n\n        xml = builder.ToString();\n    }\n\n    return xml;\n}	0
3962856	3962663	How do I prevent Lotus Notes users from forwarding or copying a message sent via System.Net.Mail?	mail.Headers.Add("Sensitivity", "Company-Confidential");	0
10551249	10551200	How to check if a word contains a character within a string?	var words = text.Split(" ");\n\n        foreach (var word in words)\n            if (word.Contains("lookup"))\n                Console.WriteLine("found it");	0
27017092	27016996	newid() as column default value	newid()	0
3909813	3909758	Running IronPython object from C# with dynamic keyword	var source =\n            @"\nclass Hello:\ndef __init__(self):\n    pass\ndef add(self, x, y):\n    return (x+y)\n\n";\n\n        var engine = Python.CreateEngine();\n        var scope = engine.CreateScope();\n        var ops = engine.Operations;\n\n        engine.Execute(source, scope);\n        var pythonType = scope.GetVariable("Hello");\n        dynamic instance = ops.CreateInstance(pythonType);\n        var value = instance.add(10, 20);\n        Console.WriteLine(value);\n\n        Console.WriteLine("Press any key to exit.");\n        Console.ReadLine();	0
19209740	19209688	Cannot insert Phone Number into Database (MS Access File)	DBcmd.CommandText = "INSERT INTO tbl_ClientInfo (FirstName, LastName, Address, ZipCode, " + \n                    "City, State, Country, [Language], PhoneNr, MobileNr)" + \n                    "VALUES (@FirstName, @LastName, @Address, @ZipCode, " + \n                    "@City, @State, @Country, @Language, @PhoneNr, @MobileNr)";	0
18484232	18483972	How can i create sublist inside a xml	var TRANSACTIONS=new XElement("TRANSACTIONS");\nTRANSACTIONS.Add(new XElement("TRANSACTION",new XElement("TYPE",4)));\nTRANSACTIONS.Add(new XElement("TRANSACTION",new XElement("TYPE",5)));\nTRANSACTIONS.Add(new XElement("TRANSACTION",new XElement("TYPE",6)));	0
22680647	22680600	multiplication and division with decimals	decimal mLon1 = 0;\ndecimal mLat1 = 0;\ndecimal mFactor = 111021;\ndecimal mRadius = 100;\ndecimal mLat = (decimal)12.123;\ndecimal mLon = 0;\nmLon1 = mLon - mRadius / (decimal)Math.Abs(Math.Cos(((Math.PI / 180) * (double)mLat)) * (double)mFactor);\nmLat1 = mLat - (mRadius / mFactor);	0
21034398	21034258	Password validation REGEX to disallow whitespaces	^((?!.*[\s])(?=.*[A-Z])(?=.*\d).{8,15})	0
10342233	10342022	NHibernate Criteria restriction with database-executed SHA1?	ISQLFunction sqlAdd = new VarArgsSQLFunction("(", "+", ")");\nvar concat = Projections.SqlFunction(sqlAdd, NHibernateUtil.String, Projections.Property("ObjectProperty1"), Projections.Property("ObjectProperty2"));\nvar sha1 = Projections.SqlFunction("SHA1", NHibernateUtil.String, concat);\n...\nsession.CreateCriteria<Car>().Add(Expression.Eq(sha1, "hash"));	0
18887052	18886957	Search in datagrid using combo box	SqlDataAdapter adpt = new SqlDataAdapter(string.Format("Select ColumName from TableName where Field like '%{0}%'", \n                 comboBox_Search.Text), sqlcon);	0
9833526	9833453	Inserting data into multiple access tables at once in C# (OLEDB)	dbc.SetCommand("INSERT INTO publishing_info ([ID], [Author], [DateTime], [Publisher], [Pages], [ISBN_NO]) " +\n           "VALUES (" +\n           "(SELECT([ID] FROM inventory " +\n           "WHERE inventory.CallNumber=@CALLNUMBER AND inventory.Title=@TITLE AND inventory.ImageLocation=@IMAGELOC), " +\n           "@AUTHOR, @DATETIME, @PUBLISHER, @PAGES, @ISBN);");	0
1482071	1313190	Defining a User with User.Identity.Name in controller constructor	public class CustomControllerClass : Controller\n{\n    public User CurrentUser;\n\n    protected override void Initialize(System.Web.Routing.RequestContext requestContext)\n    {\n        base.Initialize(requestContext);\n\n        if (requestContext.HttpContext.User.Identity.IsAuthenticated)\n        {\n            string userName = requestContext.HttpContext.User.Identity.Name;\n            CurrentUser = UserRepository.GetUser(userName);\n            ViewData["CurrentUser"] = CurrentUser;\n        }\n        else\n            ViewData["CurrentUser"] = null;\n    }\n}	0
20123955	20123820	Convert a list of a custom class to an object array	var properties = typeof(customclass).GetProperties(BindingFlags.Public | \n                          BindingFlags.Instance).OrderBy(x => x.Name).ToList();\n\nList<customclass> BMrep = somefunction();\nvar retdata = new object[BMrep.Count, properties.Count];\n\nfor (int i = 0; i < BMrep.Count; i++)\n{\n    for (int j = 0; j < properties.Count; j++)\n    {\n        retdata[i, j] = properties[j].GetValue(BMrep[i], null);\n    }\n}\n\nreturn retdata;	0
16840310	16840130	Reuse catch for all catches	try\n{ \n    throw new CustomException("An exception.");\n}\ncatch (Exception ex)\n{\n   if (ex is CustomException)\n   {\n        // Do whatever\n   }\n   // Do whatever else\n}	0
1445215	1445201	Is there a standard interface in .NET containing a single EventHandler	System.EventHandler<TEventArgs>	0
1637053	1636985	Converting string to decimal	CultureInfo c = CultureInfo.CreateSpecificCulture(CultureInfo.CurrentCulture.Name);\nc.NumberFormat.CurrencyNegativePattern = 14; // From MSDN -- no enum values for this\nc.NumberFormat.CurrencySymbol = "USD";\n\ndecimal d = Decimal.Parse("(USD 92.90)", NumberStyles.Currency, c);	0
9152560	9152500	c# update listbox without 'lag'	Debug.WriteLine()	0
34394804	34394732	Protect Winform Application/Sql Database From Copying	sql-server	0
16243148	16243058	Form in masterpage shows as white div ONLY in IE9	height:100%	0
6870582	6870560	Splitting a query string?	Request.QueryString("SubPage")	0
34477359	34476521	Using Variable To Access WPF Element	...\nint PageToAccess = 2;\n((Control)FindName("DocumentPage" + PageToAccess)).Height = 200;\n...	0
14343105	14342482	Find all quarters between 2 dates	public IEnumerable<DateTime> GetAllQuarters(DateTime current, DateTime past)\n        {\n            var curQ = (int)Math.Ceiling(current.Month / 3.0M);\n            var lastQEndDate = new DateTime(current.Year, curQ * 3, 1).AddMonths(-2).AddDays(-1);\n\n            do\n            {\n                yield return lastQEndDate;\n                lastQEndDate = lastQEndDate.AddMonths(-3);\n            } while (lastQEndDate > past);\n        }	0
19055730	19055545	Activating logging for a Winform Application	Trace.Flush	0
12774064	12684560	Update registry changes of WISP (Windows Ink Service Platform) with C#	internal static void Notify_SettingChange()	0
12258785	12258678	How to make a CheckBoxList have unique items when a new item is added to it?	protected void Button_Click(object sender, EventArgs e)\n{\n    int q1 = Convert.ToInt16(TextBox1.Text);\n\n    string t1 = DropDownList1.SelectedItem.ToString().Trim();\n    int start = 1;\n    string checkBoxValue = string.Concat(t1, start);\n    while (CheckBoxList1.Items.Cointains(new ListItem(checkBoxValue)))\n    {\n        start++;\n        checkBoxValue = string.Concat(t1, start);\n    }\n\n    for (int i = start; i <= start + q1 - 1; i++)\n    {\n        CheckBoxList1.Items.Add(string.Concat(t1, i));\n    }\n\n    TextBox1.Text = "";\n}	0
2886227	2886155	How do I get back results running a VB Script from C#?	Process vbsProcess = new Process();\nvbsProcess.StartInfo.FileName = "yourscript.vbs";\nvbsProcess.StartInfo.UseShellExecute = false;\nvbsProcess.StartInfo.RedirectStandardOutput = true;\nvbsProcess.OutputDataReceived += new DataReceivedEventHandler(YourOutputHandler);\nvbsProcess.Start();\nvbsProcess.WaitForExit();	0
3220619	3220497	Forcing the creation of a WPF Window's native Win32 handle	IntPtr hWnd;\n  WindowInteropHelper helper = new WindowInteropHelper(wnd);\n\n  WindowState prevState = wnd.WindowState;\n  bool prevShowInTaskBar = wnd.ShowInTaskbar;\n\n  wnd.ShowInTaskbar = false;\n  wnd.WindowState = WindowState.Minimized;\n  wnd.Show();\n  hWnd = helper.Handle;\n  wnd.Hide();\n\n  wnd.ShowInTaskbar = prevShowInTaskBar;\n  wnd.WindowState = prevState;	0
12015476	12015447	Using linq to extract titles from sitemap files	XElement xelement = XElement.Load(Server.MapPath("~/web.sitemap"));\n    var urlList = xelement.Descendants().Attributes()\n       .Where(x => x.Name == "title")\n       .Select(x => x.Value);\n\n    foreach (string s in urlList)\n    {\n\n    }	0
5040674	5040656	static method with private methods within it [C#]	private static	0
6360388	6360284	Convert LDAP AccountExpires to DateTime in C#	DateTime dt = new DateTime(1601, 01, 02).AddTicks(129508380000000000);	0
817810	784155	UserControl as an interface, but visible in the Designer	foreach(Control control in this.Controls)\n{\n    cName = control as ICustomerName;\n    if (cName != null) break;\n}	0
26889824	26888630	Read Platform information from .msi	using Microsoft.Deployment.WindowsInstaller;\nusing(Database database = new Database(PATH_TO_MSI, DatabaseOpenMode.ReadOnly))\n{\n  Console.WriteLine(database.SummaryInfo.Template);\n}	0
22019668	22019041	Automapper custom resolvers	Mapper.CreateMap<Conference,Model>()\n     .ForMember(c => c.Id, op => op.MapFrom(v => v.Id))\n     .ForMember(c => c.NumberOfTables, op => op.MapFrom(v => v.NumberOfTables))\n      .ForMember(c => c.Peoples, op =>\n                        op.ResolveUsing<CustomConvert>()\n                            .FromMember(x => x.Peoples));	0
6817202	6816032	C# Reflection, AppDomain: Execute same assembly from different folders	AppDomain myDomain = AppDomain.CreateDomain("MyDomain");\n\nstring pathToTheDll = "C:\\SomePath\\MyAssembly1.dll";\nobject obj = myDomain.CreateInstanceFromAndUnwrap(pathToTheDll, "MyAssembly1.TypeName");\nType myType = obj.GetType();\n\nmyType.InvokeMember("SomeMethodName", BindingFlags.InvokeMethod, null, obj, null);\n\nAppDomain.Unload(myDomain);	0
3666044	3666015	Insert with select subquery using SqlCommand	INSERT INTO [Projects] \nSELECT '1', 'None', '2', '2010/09/08 10:36:30 AM', 4, 1, 4, '6', '', 'n/a', 'no', 'n/a', 'None', 0, 'n/a', 'n/a', 'no', 'A3', 'no', 'Blnk', 'aa',\nstatus.statusID from status where name = 'STOPPED'	0
14364651	14363920	Checking internet connectivity in Windows8 via C# fails	Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>\n            {\n                if (this.Frame != null)\n                {\n                    Frame.Navigate(typeof(NetworkDisconection));\n                }\n            });	0
16166791	16163490	Set itextsharp textfield to be readonly	text.Options = TextField.READ_ONLY;	0
11206524	11206452	Return <list> values from method	public List<Appointment> GetAppointments()      \n{\n    return dataEntities.Appointments\n                       .Where(a => a.PATIENTID == PatientId)\n                       .Select(a => new OtherNamespace.Appointment \n                                    {\n                                        Id = a.Id,\n                                        Name = a.Name,\n                                        // etc.\n                                    })\n                       .ToList();\n}	0
15306512	15306437	Passing 2 parameters to a single class through map[x][y]	public overrride InnerMapArray this[int x, int y] { ... }	0
8473297	8473261	How to disable a button after 1st click	protected void Button3_Click(object sender, EventArgs e)\n{\n   Button3.Enabled = false;\n   //rest of code\n}	0
18498599	18498509	Dynamic Cast in C#	abstract class Rack\n{\n   public abstract void GetData();\n}\n\nclass ChildRack1 : Rack\n{\n    public override void GetData(){}\n}\n\nclass ChildRack2 : Rack\n{\n    public override void GetData(){}\n}\n\nclass Channel\n{\n    private Rack rack1;\n    private Rack rack2;\n    public Channel()\n    {\n\n    }\n\n    public Channel(Rack h1, Rack  h2)\n    {\n        rack1 = h1;\n        rack2 = h2;\n    }\n\n    public void send()\n    {\n\n        rack1.GetData();\n    }\n\n}	0
10952006	10951204	Linq-to-SQL reverse contains	List<string> words = Search.GetTags(q);\n using(ShapesDataContext context = new ShapesDataContext())\n {\n   IQueryable<Shape> query = Enumerable.Empty<Shape>().AsQueryable();\n   foreach (var word in words)\n   {\n     query = query.Union(context.Shapes.Where(x => x.Title.Contains(word) || x.Description.Contains(word)));\n   }	0
17733566	17732338	Windows Phone - C# - How do I create a TextBox in C#	// Add the last item to the listbox again\n    listBox.Items.Add(listBox.Items.Last());\n\n    // Place the textbox in the previous item\n    listBox.Items[listBox.Items.Count - 2] = new TextBox();	0
5646809	5645493	FFmpeg file conversion formats and file extensions	ffmpeg -i input.avi	0
9193945	9193739	How to add rows dynamically to the GridView based on the TextBox value?	gv.DataSource = Enumerable.Range(0, int.Parse(txtCount.Value))\n               .Select (e => new \n               { \n                  RTDetailID = "", \n                  AssyNo = "", \n                  Position = "-1"\n               });\ngv.DataBind();	0
18897605	18896995	combine two datetime to one and use it in linq	var sample =\n    (\n        from e in dataContext.tblA.Include("tblB")\n        where e.Active == true && System.Data.Objects.EntityFunctions.CreateDateTime(e.DateA.Year, e.DateA.Month,e.DateA.Day,e.DateB.Hour,e.DateB.Minute,e.DateB.Second) >= DateTime.Now\n        select new \n        {\n            ...\n        }\n    ).ToList();	0
7209916	7209834	Launch a program from ASP.NET C#	ProcessStartInfo psi = new ProcessStartInfo();\npsi.FileName = @"D:/Path to /My/Program to be run.exe";\npsi.WorkingDirectory = IO.Path.GetDirectoryName(psi.FileName);\nDiagnostics.Process.Start(psi);	0
432759	432753	How to check password before decrypting data	IEnumerable<T>	0
504875	504814	How can I tell if a drag and drop operation failed?	var ret = DoDragDrop( ... );\nif(ret == DragDropEffects.None) //not successfull\nelse // etc.	0
26315292	26315193	Windows phone 8 C#: How to parse JSON Array of Array of objects	JArray jsonarray = JArray.Parse("Your Json String Here");\nvar dict = (JArray)JsonConvert.DeserializeObject(Convert.ToString(jsonarray));\nforeach (var obj in dict[0])\n{\n  Debug.WriteLine(obj["condition_name"]);\n}	0
11186327	11186154	Rich Text Box how to highlight text block without select	TextRange tr = new TextRange(position, nextPosition);\nvar Br = new SolidColorBrush(Color.FromScRgb(alpha, 1f, 1f, 0f));\ntr.ApplyPropertyValue(TextElement.BackgroundProperty, Br);	0
18263681	18219758	Highlight data point on line-chart based on datetime interval (within half day) c# - Visual Studio 2008	// Scan through series and find the nearest datapoint within a given time interval\n            foreach (DataPoint pt in calCheckChart.Series[0].Points)\n            {\n                // Initialize point attributes.\n                pt.MarkerStyle = MarkerStyle.None;\n                // Check if the cursor's x-value is the near a point in series, and if so highlight it\n                if (pt.XValue > calCheckChart.ChartAreas[0].CursorX.Position - 0.4 && pt.XValue < calCheckChart.ChartAreas[0].CursorX.Position + 0.5)\n                {\n                    pt.MarkerStyle = MarkerStyle.Circle;\n                    pt.MarkerSize = 8;\n                    // toolStripStatusLabel1.Text = pt.YValues[0].ToString();\n                }\n            }\n\n // ...	0
5003137	5002909	Getting The ASCII Value of a character in a C# string	foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))\n    Console.Write(b.ToString());	0
8998278	8997632	How to validate data in WPF and set default value?	public class IntConverter : IValueConverter\n{\n    public object Convert(object value,\n                          Type targetType,\n                          object parameter,\n                          CultureInfo culture)\n    {\n        if (value is int?)\n        {\n            int? intValue = (int?)value;\n            if (intValue.HasValue)\n            {\n                return intValue.Value.ToString();\n            }\n        }\n\n        return Binding.DoNothing;\n    }\n\n    public object ConvertBack(object value,\n                              Type targetType,\n                              object parameter,\n                              CultureInfo culture)\n    {\n        if(value is string)\n        {\n            int number;\n            if (Int32.TryParse((string)value, out number))\n            {\n                return number;\n            }\n        }\n\n        return null;\n    }\n}	0
1854686	1854632	Save a ListView into Settings.settings?	StringWriter output = new StringWriter(new StringBuilder());\nXmlSerializer s = new XmlSerializer(this.GetType());\ns.Serialize(output,this);\nvar result = output.ToString()	0
4748941	4748904	Extract a purchase order # from a string in C# and put it in another string	const string refString = "PO NO.";\n        string aLine = "Widget PO NO. 1234";\n\n        string orderNumb = aLine.Substring(aLine.LastIndexOf(refString) + refString.Length).Trim();	0
32330745	32321950	Make text appear for 5 seconds in Unity	#pragma strict\n\npublic var myText : GameObject; // Assign the text to this in the inspector\n\nfunction Start() {\nyield WaitForSeconds (5);\nmyText.SetActive( true ); // Enable the text so it shows\nyield WaitForSeconds (5);\nmyText.SetActive( false ); // Disable the text so it is hidden\n}	0
7187901	7187774	Could I use C# to invoke Output as XML feature of SQL Server?	using(SqlConnection cn = new SqlConnection("data source=(local);initial catalog=pubs;.....")) {\n        cn.Open();\n        SqlCommand cmd = new SqlCommand("SELECT * FROM authors FOR XML AUTO, XMLDATA", cn);\n\n        XmlReader xmlr = cmd.ExecuteXmlReader();\n        xmlr.Read();\n        while(xmlr.ReadState != ReadState.EndOfFile) {\n                    Console.WriteLine(xmlr.ReadOuterXml());\n        }                       \n   }	0
18796420	18796262	Cannot read from txt file although the file close	using (var stream = new StreamReader( File.Open(_file, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)))\n     {\n         string str = stream.ReadToEnd();\n         int x = str.LastIndexOf('\n');\n         string lastline = str.Substring(x + 1);                              \n     }	0
2762422	2762408	how to order a group result with Linq?	var queryResult = from records in container.tableWhatever \n                  where records.Time >= DateTime.Today \n                  group records by tableWhatever.tableHeader.UserId into userRecords \n                  select new\n                  {\n                       UserID = userRecords.Key,\n                       Records = userRecords.OrderByDescending( u => u.Time )\n                  };	0
19668361	19578408	Multiple route with multiple parameters MVC4	routes.MapRoute(\n    name: "SubmitBid",\n    url: "Tender/SubmitBid/{id}/{bidId}/",\n    defaults: new \n                { \n                    controller = "Tender", \n                    action = "SubmitBid", \n                    id = UrlParameter.Optional, \n                    bidId = UrlParameter.Optional \n                });\n\nroutes.MapRoute(\n    name: "Tender",\n    url: "Tender/Create/{id}/{templateId}",\n    defaults: new \n                { \n                    controller = "Tender", \n                    action = "Create", \n                    id = UrlParameter.Optional, \n                    templateId = UrlParameter.Optional \n                });\n\n// Default route, keep this at last for fall-back.\nroutes.MapRoute(\n    name: "Default", \n    url: "{controller}/{action}/{id}", \n    defaults: new \n                { \n                    controller = "Home", \n                    action = "Index", \n                    id = UrlParameter.Optional \n                });	0
13228022	13227828	How to create Microsoft.Office.Interop.Word.Document object from byte array, without saving it to disk?	Application app = new Application();\n\nbyte[] wordContent = GetBytesInSomeWay();\n\nvar tmpFile = Path.GetTempFileName();\nvar tmpFileStream = File.OpenWrite(tmpFile);\ntmpFileStream.Write(wordContent, 0, wordContent.Length);\ntmpFileStream.Close();\n\napp.Documents.Open(tmpFile);	0
21943568	21943355	LINQ query limits returned values to those matched in List<String>	(from r in db.Restaurants where r.Restaurant_Name.StartsWith(restName) \n&& r.any(c=>test.contains(r.Restaurant_Name))\nselect r.Restaurant_Name).Take(matchingCount).toList();	0
11110968	11110900	C# - Foreach loop with if statement	void()\n{\n    var testWasTrue = false;\n    foreach()\n    {\n        if()\n        {\n            testWasTrue = true;\n            break;  // break out of the "foreach"\n        }\n    }\n\n    if( !testWasTrue ) {\n        //code I want to skip if "if" statement is true\n    }\n\n}	0
19621106	19620965	Splitting a txtfile of JSONs into individual strings of JSON objects	string[] splits = Regex.Split(txtfile, @"(?<=\}),");	0
3472570	3470327	Autogenerating schema from NHibernate attribute annotated types	new NHibernate.Tool.hbm2ddl.SchemaExport(NHibernateConfiguration).Create(false, true);	0
32480713	32478731	How to make an existing type in an assembly to implement an interface in .Net	internal class Program {\n    private static void Main(string[] args) {            \n        // suppose it's from another assembly, and you don't have direct reference to type\n        var c = Activator.CreateInstance(typeof(MyClass)); \n        IMyClass iface = c.ActLike<IMyClass>();\n        iface.method1();\n        Console.ReadKey();\n    }\n}\n\npublic class MyClass\n{\n    public void method1() {\n        Console.WriteLine("Method 1");\n    }\n\n    public void method2() {\n        Console.WriteLine("Method 2");\n    }\n}\n\npublic interface IMyClass {\n    void method1();\n    void method2();\n}	0
8029410	8029276	Get text with correct font from pptx with Openxml	using System;\nusing System.Linq;\nusing DocumentFormat.OpenXml.Packaging;\nusing DocumentFormat.OpenXml.Drawing;\n\n\nnamespace OpenXmlGetPowerpointTextInfo\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            using (PresentationDocument myPres = PresentationDocument.Open(@"test.pptx", true))\n            {\n                PresentationPart presPart = myPres.PresentationPart;\n                //SlidePart slide = presPart.GetPartsOfType<SlidePart>().FirstOrDefault();\n                SlidePart[] slidePartList = presPart.SlideParts.ToArray();\n                foreach (SlidePart part in slidePartList)\n                {\n                    RunProperties[] runProList = part.Slide.Descendants<RunProperties>().ToArray();\n                    foreach (RunProperties r in runProList)\n                   {\n                       Console.WriteLine(r.FontSize.Value);\n                   }\n                }\n            }\n        }\n    }\n}	0
22557511	22409459	In hight chart how can i show yAxis value on xAxis?	var chart = new Highcharts.Chart({\n    chart: {\n        renderTo: 'container'\n    },\n    xAxis: {\n        categories: ['01/02/2012', '01/03/2012', '01/04/2012', '01/05/2012', '01/06/2012', '01/07/2012'],\n        labels: {\n            formatter: function () {\n                var index = this.axis.categories.indexOf(this.value);\n                var points = this.axis.series[0].options.data;\n                return points[index];\n            }\n        }\n    },\n\n    series: [{\n        data: [29.9, 71.5, 106.4, 129.2, 144.0, 176.0]\n    }]\n});	0
16270656	16270634	How to call a collection that is a number	db.getCollection('15').find();	0
4554167	4554116	How to check if a windows service is installed in C#	// add a reference to System.ServiceProcess.dll\nusing System.ServiceProcess;\n\n// ...\nServiceController ctl = ServiceController.GetServices()\n    .FirstOrDefault(s => s.ServiceName == "myservice");\nif(ctl==null)\n    Console.WriteLine("Not installed");\nelse    \n    Console.WriteLine(ctl.Status);	0
28032350	28032262	How to add foreign key to entity	public int TransactionSubcategoryId { get; set; }\npublic int OwnerMemberId { get; set; }	0
6470304	6470255	Open url with IE instead of default browser	System.Diagnostics.Process.Start("iexplore.exe", "http://sp.path.to/your/file.doc")	0
10713636	10529629	How to get PdfWriter for the current page in the multipage document?	PdfAppearance ap = newPage.CreateAppearance(rect.Width, rect.Height);\nannot.SetAppearance(PdfAnnotation.APPEARANCE_NORMAL, ap);\nannot.SetPage();\nstamper.AddAnnotation(annot, i);\nsd.Dispose();\nsd.Close();	0
24699137	24697960	How get DirectoryServicesCOMException from InnerException?	if (e.InnerException is DirectoryServicesCOMException)\n{\n    DirectoryServicesCOMException innerException = (DirectoryServicesCOMException)e.InnerException;\n    // do whatever is correct with these kind of exception\n}	0
2831832	2831809	How would I use reflection to call all the methods that has a certain custom attribute?	var methods = typeof( MyClass ).GetMethods( BindingFlags.Public );\n\nforeach(var method in methods)\n{\n    var attributes = method.GetCustomAttributes( typeof( MyAttribute ), true );\n    if (attributes != null && attributes.Length > 0)\n        //method has attribute.\n\n}	0
24422996	24421403	populating xml template at run time from object collection at runtime	using(XmlWriter writer = XmlWriter.Create("output.xml"))\n{\n    writer.WriteStartElement("Document");\n    writer.WriteStartElement("Header");\n\n    writer.WriteStartElement("OrgName");\n    writer.WriteString("abc");\n    writer.WriteEndElement();\n\n    writer.WriteStartElement("OrgAddress");\n    writer.WriteString("asd dfs 999 dfsd");\n    writer.WriteEndElement();\n\n    // End Header\n    writer.WriteEndElement();\n\n    writer.WriteStartElement("Detail");\n\n    writer.WriteStartElement("EmpId");\n    writer.WriteString("100");\n    writer.WriteEndElement();\n\n    // End Detail\n    writer.WriteEndElement();\n\n    // End Document\n    writer.WriteEndElement();\n}	0
27416287	27415586	Using LINQ to generate prime numbers	var numbers = Enumerable.Range(2, (int)(20000 * (Math.Log(20000) + Math.Log(System.Math.Log(20000)) - 0.5)))\n                .AsParallel()\n                .WithDegreeOfParallelism(Environment.ProcessorCount) \n                .WithExecutionMode(ParallelExecutionMode.ForceParallelism)\n                .WithMergeOptions(ParallelMergeOptions.NotBuffered) // remove order dependancy\n                .Where(x => Enumerable.Range(2, x - 2)\n                                      .All(y => x % y != 0))\n                .TakeWhile((n, index) => index < 20000);\nstring result = String.Join(",",numbers.OrderBy (n => n));	0
29025698	29025575	Find X509 certificate from store based on Thumbprint	Certificate[1].Thumbprint	0
4740867	4740764	WPF C# Custom UserControl How To add a Property which accepts an Binding	public IObservable<object> BindingList\n{\n  get { return (IObservable<object>)base.GetValue(BindingListProperty); }\n  set { base.SetValue(BindingListProperty, value); }\n}\n\npublic static DependencyProperty BindingListProperty =\n  DependencyProperty.Register(\n  "BindingList",\n  typeof(IObservable<object>),\n  typeof(CustomControl),\n  new PropertyMetadata(null));	0
10543153	10540482	C# - Windows Mobile - Pairing with Zebra RW 420	BluetoothAddress addr = ...\nGuid serviceClass;\nserviceClass = BluetoothService.SerialPort;\nvar ep = new BluetoothEndPoint(addr, serviceClass);\nvar cli = new BluetoothClient();\ncli.Connect(ep);\nStream peerStream = cli.GetStream();\npeerStream.Write ...	0
25809541	25809018	Parsing JSON and looping through replies	static void Main(string[] args)\n    {\n\n        DB db = new DB();\n        DataTable dtServers = db.GetDataTable("select * from SYS_Servers");\n        string htmlCode;\n        var json = "";\n        using (var webClient = new System.Net.WebClient())\n        {\n            json = webClient.DownloadString("http://www.soyoustart.com/fr/js/dedicatedAvailability/availability-data.json");\n        }\n\n        RootObject myData = JsonConvert.DeserializeObject(json, typeof(RootObject)) as RootObject;\n        foreach (var availability in myData.availability)\n        {\n            //do something with availability\n        }\n        String x = "moo";\n    }\n    public class Zone\n    {\n        public string availability { get; set; }\n        public string zone { get; set; }\n    }\n\n    public class Availability\n    {\n        public string reference { get; set; }\n        public Zone[] zones { get; set; }\n    }\n\n    public class RootObject\n    {\n        public Availability[] availability { get; set; }\n    }	0
25112706	25112339	How to get asp.net table column count programmatically	//add table first\nTable tbl = new Table();\nint columnsToAdd = 4;\nfor (int x = 0; x < columnsToAdd; x++)\ntbl.Columns.Add(new TableColumn());\n//then get table count\nint columns = tbl.Columns.Count;	0
255030	254976	Help with using ConfigurationSection to properly read from a config file	public class PaymentSection : ConfigurationSection\n{\n   // Simple One\n   [ConfigurationProperty("name")]]\n   public String name\n   {\n      get { return this["name"]; }\n      set { this["name"] = value; }\n   }\n\n}	0
13208122	13207727	order by in lambda expressions	var a = Directory.GetFiles(path)\n                 .OrderBy(p => Regex.Replace(p,@"^.*\\(\d\d)(\d\d)(\d\d\d\d).*$","$3$2$1"))	0
2389993	2389955	How to get a value from an xml directly (preferably using XPath)?	var xmlItem = root.SelectSingleNode("/Primary/Complex[@Name='comp1']/@Value");	0
30792840	30792752	Removing non alpha characters	var cleanString = new string(dirtyString.Where(Char.IsLetter).ToArray());	0
14034816	14034773	Eliminate duplicates from database	if (info.Trim() != String.Empty)\n{\n    string[] words = info.Split(',');\n    if (words.Length == 6)\n    {\n        name = words[0].Trim();\n        date = words[1].Trim();\n        place = words[2];\n        blood = words[3];\n        num = words[4];\n        address = words[5];\n    }\n\n\n    string cmdText = "INSERT INTO patients (" +\n       "firstlastname, birthdate, birthplace, bloodtype, telnum, address) " +\n       "VALUES (?,?,?,?,?,?)";\n\n    using (OleDbConnection cn = GetConnection())\n    {\n        using (OleDbCommand cmd = new OleDbCommand(cmdText, cn))\n        {\n            cmd.Parameters.AddWithValue("name", name);\n            cmd.Parameters.AddWithValue("date", date);\n            cmd.Parameters.AddWithValue("place", place);\n            cmd.Parameters.AddWithValue("blood", blood);\n            cmd.Parameters.AddWithValue("num", num);\n            cmd.Parameters.AddWithValue("address", address);\n            cmd.ExecuteNonQuery();\n        }\n    }\n}	0
10273443	10272676	WCF base web address during runtime	Uri address = OperationContext.Current.IncomingMessageHeaders.To;	0
13583313	13583259	Get List<int> from List<Customer> using linq	List<int> customerIds = customerList.Select(c => c.Id).Distinct().ToList();	0
16707514	16707160	Stored procedure date validation not check with existing dates for a particular ID	CREATE PROCEDURE Test\n@startdate DATETIME, @enddate DATETIME, @Userid INT, @Registerid INT\nAS\nBEGIN\n    SELECT Count(*)\n    FROM   leave\n    WHERE  ((UserID = @userid)\n            AND ((@startdate BETWEEN StartDate AND EndDate)\n                 AND (@Registerid <> Registerid)\n                 OR (@enddate BETWEEN StartDate AND EndDate)\n                 OR ((@startdate <= Startdate\n                      AND @enddate >= EndDate))));\nEND	0
18613234	18613050	How to bulk edit a single column in a grid view	foreach(GridViewRow row in GridView1.Rows) {\n    if(row.RowType == DataControlRowType.DataRow) {\n\n        TextBox txtbx= row.FindControl("txtbx") as TextBox;\n        //using the txtbx you can get the new values and update then to the db\n    }\n}	0
4216632	4216607	Delete folder with C#	System.IO.DirectoryInfo dir = new System.IO.DirectoryInfo("your path");\nif (dir.Exists)\n     dir.Delete(true);	0
30982290	30981550	Updating a list of objects bound to a DataGridView from a popup form	dataGridBasket.InvalidateRow(row.Index)	0
13942891	13935275	Prevent word wrap in label with AutoSize=false	public class CustomLabel : Label\n{\n    public CustomLabel()\n    {            \n    }\n\n    protected override void OnPaint(PaintEventArgs e)\n    {\n        e.Graphics.DrawString(Text, Font, new SolidBrush(ForeColor), 0, 0);\n    }\n}	0
15333405	15331818	How to Convert Double Byte String to Single Byte String?	using Microsoft.VisualBasic;\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n      string inputText = textBox1.Text;\n      string singleByteString =  Strings.StrConv(inputText, VbStrConv.Narrow, 0);\n\n      textBox2.Text = singleByteString;\n      textBox3.Text = inputText;\n}	0
6567173	6566283	Designing for S3	photos/puppy.jpg?AWSAccessKeyId=0PN5J17HBGZHT7JJ3X82\n    &Signature=rucSbH0yNEcP9oM2XNlouVI3BH4%3D\n    &Expires=1175139620	0
11532701	11532430	C# Linq Select from one to many but if in the many one is false dont return	var users = context.Messages\n            .Where(m => m.Code == "22X")\n            .GroupBy(m => m.User)\n            .Where(m => m.All(x => x.Replied == false))\n            .Select(p => p.Key);	0
1340701	1340504	I would need a little help to write this linq query	from a in (from d in AllowanceDomains _\nfrom t in AllowanceTypes _\nwhere (new integer(){1,2}).contains(t.AllowanceTypeID) and t.active = true and d.active=true _\nselect  t.allowancetypeid,tdescen =t.descen, d.allowancedomainid,ddescen=d.descen)  _\ngroup join qqq in AllowanceQties on new with {.k1 = a.allowancetypeid, .k2 = a.allowancedomainid, .k3 = 2} equals _\nnew with {.k1 = qqq.allowancetypeid, .k2 = qqq.allowancedomainid, .k3 = qqq.allowanceid} into qq = group _\nfrom q in qq.DefaultIfEmpty _\njoin u in units on if(object.equals(q.unitid,nothing),1,q.unitid) equals u.unitid _\nselect  AllowanceID =if(object.equals(q.AllowanceID,nothing),2,q.AllowanceID) ,a.tdescen,a.ddescen,qty = if(object.equals(q.qty,nothing),0,q.qty),u.descen	0
12143375	12142938	Can I access the Assembly GUID from my webconfig file	var assemblyName = "System"; // assembly to get the guid\n\n var assembly = AppDomain.CurrentDomain\n        .GetAssemblies()\n        .FirstOrDefault(a => a.GetName().Name == assemblyName);\n\n var attr = assembly\n        .GetCustomAttributes(false)\n        .OfType<GuidAttribute>()\n        .FirstOrDefault();\n\n var guid = attr.Value;	0
17161337	17160420	Splitting array within array	[-\d.]*,\[[-\d.]*,[-\d.]*,[-\d.]*,[-\d.]*,[-\d.]*],\[[-\d.]*,[-\d.]*]	0
4661382	4661160	building tab delimited files from one datatable	var groupedData = from DataRow row in dt.Rows\n                    let specimen = row["specimen"].ToString()\n                    let batch = row["batch"].ToString()\n                    let position = row["position"].ToString()\n                    group new { specimen, position } by batch;\n\nforeach (var dataGroup in groupedData)\n{\n    string fileName = string.Format(@"C:\Temp\{0}.txt", dataGroup.Key); // construct filename based on batch?\n    using (StreamWriter writer = new StreamWriter(fileName))\n    {\n        foreach (var item in dataGroup)\n        {\n            writer.WriteLine("{0}\t{1}", item.specimen, item.position);\n        }\n    }\n}	0
3345607	3345526	Need help with Linq filtering in C#	var filtered = HourList.GroupBy(h => h.id)\n                       .Select(g => new { Id = g.Key,\n                                          Hours = g.Sum(h => h.Hours)\n                                        })\n                       .Where(h => h.Hours >= 10);	0
603291	603258	How would you prevent user from adding/removing lines in a TextBox?	public class myCustomTextBox : TextBox\n{\n    protected override void WndProc(ref Message m)\n    {\n        if (m.Msg == 770) // window paste message id\n        {\n            string clipBoardData = Clipboard.GetDataObject().GetData(DataFormats.Text).ToString();\n            handlePasteEvent(clipBoardData);\n        }\n        else\n        {\n            base.WndProc(ref m);\n        }\n    }\n    private void handlePasteEvent(string pasteData)\n    {\n        // process pasted data\n    }\n}	0
1124962	1124856	Refreshing a Repeater control in an UpdatePanel with ASP.NET	protected void Page_Load(object sender, EventArgs e)\n    {\n        if(!IsPostBack)\n        {\n            this.DataBind();\n        }\n    }\n    protected void MyButton_Click(object sender, EventArgs e)\n    {\n        //Code to do stuff here...\n\n        //Re DataBind\n        this.DataBind();\n    }\n    public override void DataBind()\n    {\n        //Databinding logic here\n    }	0
9912843	9912449	How to group a period of time into yearly periods ? (split timespan into yearly periods)	DateTime start = new DateTime(2012,4,1); \nDateTime end = new DateTime(2016,7,1); \n\nvar dates = from year in Enumerable.Range(start.Year,end.Year-start.Year+1)\n        let yearStart=new DateTime(year,1,1)\n        let yearEnd=new DateTime(year,12,31)\n        select Tuple.Create(start>yearStart ? start : yearStart, end<yearEnd ? end : yearEnd); \n\nIList<Tuple<DateTime,DateTime>> result = dates.ToList();	0
2234886	2234813	c# find same range of "named days" from 1 year ago	using System;\n\npublic class Test\n{\n    static void Main()\n    {\n        Console.WriteLine(SameDayLastYear(DateTime.Today));\n        Console.WriteLine(SameDayLastYear(new DateTime(2010, 12, 31)));\n    }\n\n    static DateTime SameDayLastYear(DateTime original)\n    {\n        DateTime sameDate = original.AddYears(-1);\n        int daysDiff = original.DayOfWeek - sameDate.DayOfWeek;\n        return sameDate.AddDays(daysDiff);\n    }\n}	0
21940539	21940401	How to insert into three tables at once in sql server 2012	BEGIN TRANSACTION\n\nINSERT INTO members\n(id, firstname, etc.)\nVALUES (tbMemberID.text, tbFirstName.text, etc)\n\nINSERT INTO fees\n(id, amount, etc.)\nVALUES (tbFeeID.text, tbAmount.text, etc)\n\nINSERT INTO schedule\n(id, session)\nVALUES (tbScheduleID.text, tbSession.text)\n\nCOMMIT TRANSACTION\nGO	0
20053642	20053319	How to parse marked up text in C#	string inputMessage = @"The \i{quick} brown fox jumps over the lazy dog^{note}";\nMatchCollection matches = Regex.Matches(inputMessage, @"(?<=(\\i|_|\^)\{)\w*(?=\})");\n\nforeach (Match match in matches)\n{\n    string textformat = match.Groups[1].Value;\n    string enclosedstring = match.Value;\n    // Add to Dictionary<string, TextFormats> \n}	0
1119872	1119745	Find default email client	using System;\nusing Microsoft.Win32;\n\nnamespace RegistryTestApp\n{\n   class Program\n   {\n      static void Main(string[] args)\n      {\n         object mailClient = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SOFTWARE\Clients\Mail", "", "none"); \n         Console.WriteLine(mailClient.ToString());\n      }\n   }\n}	0
11888098	11886119	Using formula to map IEnumerable of strings	HasMany(x => x.EventCodes)\n            .Table("tblSomeOtherTable")\n            .KeyColumn("EventID")\n            .Element("DisciplineCode")\n            .AsSet()\n            .ReadOnly();	0
4293862	4293713	Bind ComboBox To DataGridView Column	dgv.DataSource = ds;\ndgv.DataBind();\n\ncombobox1.ValueMember = "cLoadName";\ncombobox1.DisplayMember = "cLoadName";\ncombobox1.DataSource = ds;\ncombobox1.DataBind();	0
21565644	21563214	Big trouble by trying to implement an Background Agent for WP8 App	protected override void OnInvoke(ScheduledTask task)\n{ \n Deployment.Current.Dispatcher.BeginInvoke( async () =>\n {\n      await DataLib.DataLib.Daten();\n      NotifyComplete();\n });\n}	0
24205580	24205491	DataGrid not updating with ObservableCollection	public string SignalName\n    {\n        get\n        {\n            return _signalName;\n        }\n        set\n        {\n            _signalName = value;\n            OnPropertyChanged("SignalName"); //Added\n        }\n    }\n\n    public string SignalValue\n    {\n        get\n        {\n            return _signalValue;\n        }\n        set\n        {\n            _signalValue = value;\n            OnPropertyChanged("SignalValue"); //NOTE: quotation marks added\n        }\n    }	0
4552698	4552672	How do I validate height for format x'x"?	string height="5'6\"";\n\n      Regex r = new Regex("^\\d+'\\d+\"$");\n      Match m = r.Match(height);\n      if (m.Success)\n      {\n            ' Yes!\n      }	0
16640540	16640479	Unable to call connection string from web config file	"data source=sahil-pc\sqlexpress; database=abadakDb; Integrated Security=true " providerName="System.Data.SqlClient"	0
634651	634614	Regular expression for a single word	foreach (string batch in Regex.Split(script, "^GO$\\n", RegexOptions.IgnoreCase | RegexOptions.Multiline))\n{\n    yield return batch;\n}	0
2840380	2840361	repalcing the string value	double value = double.Parse(str);\nConsole.WriteLine(value.ToString("##.##"));	0
19181528	19181144	Get all the months between dates in MM/YYYY format	List<string> result = new List<string>();\nDateTime startDate = new DateTime(2012, 1, 8);\nDateTime endDate = new DateTime(2013, 1, 3);\nDateTime temp = startDate;\nendDate = new DateTime (endDate.Year, endDate.Month, DateTime.DaysInMonth(endDate.Year,endDate.Month));\nwhile (temp <= endDate)\n{\n    Console.WriteLine((string.Format("{0}/{1}", temp.Month, temp.Year));\n    temp = temp.AddMonth(1);\n}	0
22498613	22498436	How To create Extensible WCF service	[ServiceContract]\nIDestinationHelper\n{\n  [OperationContract]\n  IEnumerable<Waypoint> ReachDestination(string transportationMode);\n\n  [OperationContract]\n  IEnumerable<string> GetAvailabletransportationModes();\n}\n\nIDestinationHelperService : IDestinationHelper\n{\n  public IEnumerable<Waypoint> ReachDestination(string transportationMode)\n  {\n     // decide return value by transportation mode. Use a switch statement, dependency injection, IoC containers, whatever you want\n  }\n\n  public IEnumerable<string> GetAvailabletransportationModes()\n  {\n     // decide return value by getting all modes from wherever you decided upon above.\n  }\n}	0
13866082	13865900	Inserting empty datarows into a Grid	DataTable dt = new DataTable();\ndt.Columns.Add("Spots");\ndt.Columns.Add("CompanyName");\n\nint i = 0;\nwhile(i<10)\n{\n   DataRow dr = dt.NewRow();\n   dr["Spots"] = "";\n   dr["CompanyName"] = "";\n\n   dt.Rows.Add(dr);\n   i++;\n}\n\nMyGrid.DataSource = dt;\nMyGrid.DataBound();	0
25732402	25732150	Enumerating to infinity in more than two dimensions	for(limit=0;;++limit) {\n  for(i0=0; i0<=limit; ++i0) {\n    for(i1=0; i1<=limit-i0; ++i1) {\n      for(i2=0; i2<=limit-i0-i1, ++i2) {\n        for(i3=0; i3<=limit-i0-i1-i2, ++i3) {\n          int i4 = limit-i0-i1-i2-i3;\n          //do stuff with i0, i1, i2, i3, i4; break when had enough\n      }}}}}}	0
5560075	5543877	Latitude/Longitude Combinations within Bounding Box	(llat, llong) -> (x = llong * cos(llat), y = llong)	0
7178155	7177524	Xml serialization - collection attribute	[XmlElement("D")]\npublic List<D> D { get; set; }	0
1927545	1927532	RegEx for extracting number from a string	String data = \n  Regex.Match(@"PO\d{10}", "PurchaseOrderPO1000000109.pdf", \n    RegexOptions.IgnoreCase).Value;	0
19479797	19479451	How to send a list of object from my MainPage.xaml to another page	{\n     var i= PhoneApplicationService.Current.State["yourparam"];\n\n     //convert object to list//\n     iList1 = (IList) i ; \n     lstpro.ItemsSource = iList1;\n\n}	0
17870893	17870285	Fiddler speeds up HTTPClients Requests even without Reuse Connections option	ServicePointManager.DefaultConnectionLimit = 300; // or sth	0
31837376	31837133	Parse a date/time string in specific format	DateTime d;\nDateTime.TryParseExact(target,"dd/MMM/yyyy:hh:mm:ss zzzz", CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out d);	0
16939278	16938999	Sort Tasks into order of completition	Task.WhenAny	0
21455746	21454715	Query JSON With Unknown Structure	private  List<string> LoadFirstNames(string json)\n{\n   JObject o = JObject.Parse(json);\n   List<string> firstNames = new List<string>();\n   foreach(var token in o.GetPropertyValues())\n   {\n    FindFirstName(token, firstNames);\n   }\n\n   return firstNames;\n}\n\nprivate void FindFirstName(JToken currentProperty, List<string> firstNamesCollection)\n{\n   if(currentProperty == null)\n   {\n     return;\n   }\n\n   if(currentProperty["firstName"] != null)\n   {\n       firstNamesCollection.Add(currentProperty["firstName"]);\n   }\n\n   foreach(var token into currentProperty.Values())\n   {\n     FindFirstName(token , firstNamesCollection);\n   }\n\n}	0
2934109	2934098	Add a datatable to a data set	DataSet.Tables[0].Copy()	0
22367780	22367720	If one checkbox is checked, set the other to unchecked	private void chkBuried_CheckedChanged(object sender, EventArgs e)\n{\n    chkAboveGround.Checked = !chkBuried.Checked;\n}\nprivate void chkAboveGround_CheckedChanged(object sender, EventArgs e)\n{\n    chkBuried.Checked = !chkAboveGround.Checked;\n}	0
4976325	4976273	Filtering SelectListItem using a string array.-mvc	AgentsNotselected = AvaliableAgents.Where(a => !AvailableAgentSelected.Contains(a.Value));	0
6987065	6986928	Enforcing a model's boolean value to be true using data annotations	using System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\nusing System.Threading.Tasks;\nusing System.Web.Mvc;\n\nnamespace Checked.Entitites\n{\n    public class BooleanRequiredAttribute : ValidationAttribute, IClientValidatable\n    {\n        public override bool IsValid(object value)\n        {\n            return value != null && (bool)value == true;\n        }\n\n        public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)\n        {\n            //return new ModelClientValidationRule[] { new ModelClientValidationRule() { ValidationType = "booleanrequired", ErrorMessage = this.ErrorMessage } };\n            yield return new ModelClientValidationRule() \n            { \n                ValidationType = "booleanrequired", \n                ErrorMessage = this.ErrorMessageString \n            };\n        }\n    }\n}	0
23237631	23237537	Removing items from collection	foreach(string id in list) {\n    //get item which matches the id\n    var item = myitemcollection.Where(x => x.id == id);\n    //remove that item\n    myitemcollection.Remove(item);\n}	0
12728966	12728844	How to pass a method with optional parameters as an argument?	CallMethod(() => Foo()); // Compiler will use default within the lambda.\n...\npublic void Foo(bool x = true) { ... }\n\npublic void CallMethod(Action action) { ... }	0
8546763	8546699	Handling generic classes that is instanciated at run-time based on database data	public Counter<T> GetCounter<T>(string columnName)\n{\n    if (columnName == "id")\n        return new Counter<T>(this._table.IDs);\n    else if (columnName == "name")\n        return new Counter<T>(this._table.Names);\n}	0
7046612	7025650	String collection values duplicated when I save it then reload it from XML	[XmlElement("AttributesCustomList")]\n    public list<string> _AttributesCustomList;\n    [CategoryAttribute("Custom"), ReadOnly(false),\n    Description("This property is customised to put new attributes")]\n    //[RefreshProperties(RefreshProperties.All)]\n    [RulesCriteria("Custom AttributesList")]\n    public list<string> AttributesCustomList\n    {\n        get { return _AttributesCustomList; }\n        set { _AttributesCustomList = value; }\n    }	0
1522897	1522884	C# Ensure string contains only ASCII	string sOut = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(s))	0
969284	969206	FileInfo compact framework 3.5 - cannot find file	FileInfo logfileInfo = new FileInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + @"\Log4Net.config");	0
3442078	3441923	Syntax highlighting in MS Word	Sub ChangeColor\n    Options.DefaultHighlightColorIndex = wdBrightGreen\n    Selection.Find.ClearFormatting\n    Selection.Find.Highlight = True\n    Selection.Find.Replacement.ClearFormatting\n    Selection.Find.Replacement.Highlight = True\n    Selection.Find.Execute Replace:=wdReplaceAll\n\n    Selection.Find.ClearFormatting\n    Selection.Find.Font.Color = wdColorBrightGreen\n    Selection.Find.Replacement.ClearFormatting\n    Selection.Find.Replacement.Font.Color = wdColorRed\n    With Selection.Find\n        .Text = ""\n        .Replacement.Text = ""\n        .Forward = True\n        .Wrap = wdFindContinue\n    End With\n    Selection.Find.Execute Replace:=wdReplaceAll\nEnd Sub	0
553842	553824	Serializing an array of integers using XmlSerializer	[XmlIgnore]\npublic int[, ,] Data { get; set; }\n\n[XmlElement("Data"), Browsable(false)]\n[EditorBrowsable(EditorBrowsableState.Never)]\npublic int[] DataDto\n{\n    get { /* flatten from Data */ }\n    set { /* expand into Data */ }\n}	0
33080924	33080802	Selecting both listbox item by just selecting on one listbox item from another listbox	private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n{\n     if (listBox2.Items.Count >= listBox1.SelectedIndex + 1)\n     {\n          listBox2.SelectedIndex = listBox1.SelectedIndex;\n     }\n}\n\nprivate void listBox2_SelectedIndexChanged(object sender, EventArgs e)\n{\n    if (listBox1.Items.Count >= listBox2.SelectedIndex + 1)\n    {\n         listBox1.SelectedIndex = listBox2.SelectedIndex;               \n    }\n}	0
21554305	21552185	Update huge SQLite databases	drop table table1;\ncreate table table1 as select * from table2;	0
146474	146439	Way to stop a program from starting up using c#?	Process[] processes = Process.GetProcessesByName(processName);\nforeach(Process process in processes)\n{\n   process.Kill();\n}	0
24635717	24635476	Get Value of a specific cell in DataGrid	if (selectedCellRow != null)\n{\n    DataGridCellsPresenter presenter = GetVisualChild<DataGridCellsPresenter>(selectedCellRow);\n\n    DataGridCell cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);\n    if (cell == null)\n    {\n        cell = (DataGridCell)presenter.ItemContainerGenerator.ContainerFromIndex(column);\n    }\n}	0
2537314	2537235	How do I get date from week, working also with 53-week years? c#	DateTime d = new DateTime(year, 1, 1);	0
20679563	20679520	Lambda expression to replace every items from the List<string> which match the string in c# .net	list = list.Select(m => m == "A" ? "C" : m).ToList();	0
16363887	16344107	URL-Encoded post parameters don't Bind to model	public class ReportRequest\n    {\n        public DateTime StartTime { get; set; }\n        public DateTime EndTime { get; set; }\n        public string FileName { get; set; }\n        public string UserName { get; set; }\n        public string Password { get; set; }\n    }	0
5849455	5849210	.NET - Getting all implementations of a generic interface?	public static bool DoesTypeSupportInterface(Type type,Type inter)\n{\n    if(inter.IsAssignableFrom(type))\n        return true;\n    if(type.GetInterfaces().Any(i=>i. IsGenericType && i.GetGenericTypeDefinition()==inter))\n        return true;\n    return false;\n}\n\npublic static IEnumerable<Type> TypesImplementingInterface(Type desiredType)\n{\n    return AppDomain\n        .CurrentDomain\n        .GetAssemblies()\n        .SelectMany(assembly => assembly.GetTypes())\n        .Where(type => DoesTypeSupportInterface(type,desiredType));\n\n}	0
30224681	30224501	c# linq select hierarchy from list where root has a certain property value	List<FileHierarchy> mylist = GetList();\nvar selected = mylist.Where(s => s.NeedsShowing.HasValue && s.NeedsShowing.Value);\nvar children = mylist.Where(c => c.ParentID.HasValue && selected.Select(s => s.ID).Contains(c.ParentID.Value));\nvar unselected = mylist.Except(selected);\nwhile (children.Any())\n{\n    unselected = unselected.Except(children);\n    var childChild = unselected.Where(c => c.ParentID.HasValue && children.Select(s => s.ID).Contains(c.ParentID.Value));\n    selected = selected.Union(children);\n    children = childChild;\n}	0
13728733	13728580	How to order documents by average aggregate of the nested childrens' property in RavenDB?	Map = locations => from l in locations\n                   select new {\n                       _ = SpatialIndex.Generate(l.Geo.Lat, l.Geo.Lon),\n                       AvgRating = l.Reviews.Average(r => r.Rating)\n                   };	0
8729769	8729165	Change the default installation folder programmatically for setup	static void Main()\n    {\n            Process setupProcess = new Process();\n            string msiFilePath = @"c:\path to msi package";\n            string targetDir = @"target dir path";\n            setupProcess.StartInfo.FileName = @"msiexec.exe /i " + msiFilePath + " TARGETDIR=\"" + targetDir + "\"";\n            setupProcess.StartInfo.UseShellExecute = false;    \n            setupProcess.Start();\n   }	0
1684968	1684736	regular expression to extract team names from "A vs B" listings	Regex test = new Regex(@"(?i)^(?:(?:Team\s+(?<team>.*?))|(?<name>.*?))(?:\s+(?<vs>v\.?s\.?)\s+)(?:(?:Team\s+(?<team>.*?))|(?<name>.*?))$");\nforeach (string input in ...)\n{\n  Match match = test.Match(input);\n  if (match.Success) \n  {\n    string team = match.Groups["team"].Value;\n    string name = match.Groups["name"].Value;\n  }\n}	0
18203444	18202678	How to load multiple files(*.xml) via XmlDocument C#	string newValue = "1234";\nXmlDocument doc;\nvar paths = new[] { "config1.xml", "config2.xml" };\npaths.ToList().ForEach(path =>\n{\n    doc = new XmlDocument();\n    doc.Load(path);\n\n    // process the document\n    var nm = new XmlNamespaceManager(doc.NameTable);\n    var a = doc.SelectSingleNode("//SomeKeyValue", nm);\n    a.InnerText = newValue;\n\n    // save the file\n    doc.Save(path);\n});	0
14644873	14644712	Adding a picture box with a mouse click WinForm	public void AddPictureBox(int x, int y)\n    {\n        try\n        {\n            PictureBox _picBox = new PictureBox();\n            _picBox.Size = new Size(100, 100);\n            _picBox.SizeMode = PictureBoxSizeMode.StretchImage;\n            _picBox.BackColor = Color.Black;\n            _picBox.Location = new Point(x, y);\n            _displayedImage.Add(_picBox);\n\n            return _picBox;\n\n        }\n        catch (Exception e)\n        {\n            Trace.WriteLine(e.Message); return null;\n        }\n    }\n\n\nprivate void MouseDown( object sender, MouseEventArgs e)\n    {\n        if (e.Button == MouseButtons.Left)\n        {\n            PictureBox pic = _testImage.AddPictureBox(e.X, e.Y);\n            if(pic != null)\n            {\n                this.Controls.Add(pic);\n                Trace.WriteLine("Picture box added");\n            }\n        }\n\n        Trace.WriteLine("Mouse Click");\n    }	0
6016869	6016179	key_down event of DateTimePicker	private void dateTimePicker1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.KeyCode == Keys.Delete || e.KeyCode == Keys.Back)\n        {\n            dateTimePicker1.Format = DateTimePickerFormat.Custom;\n            dateTimePicker1.CustomFormat = " ";\n        }\n    }\n\n    private void dateTimePicker1_ValueChanged(object sender, EventArgs e)\n    {\n        dateTimePicker1.Format = DateTimePickerFormat.Long;\n    }	0
9700858	9700817	Why can't we change the iteration variable in a foreach loop	name.Age = 1;\n// and\nnames[i].Age = 1;	0
4689462	4689308	Preventing a dialog from showing multiple times	else if (state.IsKeyDown(Keys.H))\n    {\n        if (!help.Visible)\n             help.ShowDialog();\n    }	0
22414705	22413908	ComboBox remembers SelectedIndex after changing DataSource	comboBox.DataSource = new BindingSource(list1, null);	0
2994502	2895898	Visual Studio build fails: unable to copy exe-file from obj\debug to bin\debug	[assembly: AssemblyVersion("2.0.*")]	0
1250315	1250281	c# How to sort a sorted list by its value column	SortedList<string,bool> l=new SortedList<string, bool>();\n        l.Add("a",true);\n        l.Add("a",false);\n        l.Add("b",true);\n        l.Add("b",false);\n        var orderByVal=l.OrderBy(kvp => kvp.Value);	0
1975534	1975500	How do I convert a DateTime to a Date in C#	Date d = new Date(dt);	0
19953554	19953511	Extension Method for permutations	var result = listToPermutate.Permutations();	0
9061853	9061834	Using the ternary operator to return lowest value from three variables	result = indexA < indexB ? Min(indexA, indexC) : Min(indexB, indexC);	0
18035464	18035431	Prevent flickering in ListView	EnableDoubleBuffer(myListVeiew);	0
16038790	16038218	how to insert imagepath in table	INSERT INTO employee (name,path) \nSELECT 'sarju','~/images/'+CAST(IDENT_CURRENT('employee') AS VARCHAR(50))+'.jpg'	0
813163	812894	How to interface with PKCS #11 compliant HSM device in .Net?	wspkcs11d.dll	0
32630456	32630345	Set UI Element Position to Mouse Position	Canvas.SetLeft(MousePos_Ellipse, MousePos_Point.X);\n   Canvas.SetTop(MousePos_Ellipse, MousePos_Point.Y);	0
5040869	5039441	Declaring an array of base class and instantiating inherited members	public class DataStore\n{\n     // UnderlyingDataStore is another class that manages a queue, or a linked list\n     private UnderlyingDataStore dataQueue = new UnderlyingDataStore();\n     public void addData(object data) { dataQueue.Add(data); }\n     public object getLastData() { dataQueue.getLastData(); }\n}	0
27686347	27686289	getting two lists of objects from controller to view using json and javascript	var result=new { PWs=PWs, Files=Files};\nreturn Json(result, JsonRequestBehavior.AllowGet);	0
25187854	25187361	How do I set the value of a label in a Gridview's footer template?	protected void Page_PreRender(object sender, EventArgs e)\n{\n      Label lblCreateDate = ((Label)gvMainView.FooterRow.FindControl("lblCreateDate")).Text;\n    lblCreateDate.Text = AutoDate;\n    Label lblWebsite = ((Label)gvMainView.FooterRow.FindControl("lblWebsite")).Text;\n    lblWebsite.Text = Website;\n}	0
1374330	1374317	Is it ok to use a XML column to store extra data?	[EmployeeField]\n-----------------------------------------------------\nEmployeeID    EmployeeFieldName    EmployeeFieldValue	0
2467421	2467392	How to write it in LINQ?	var res =  Enumerable.Range(50, 51).Where(n=>n%10==0);	0
11118158	11117913	How to play a beep sound clicking on a disabled control?	private void Form1_Click(object sender, EventArgs e)\n{\n  var p = PointToClient(Cursor.Position);\n  var c = GetChildAtPoint(p);\n  if (c != null && c.Enabled == false)\n    System.Media.SystemSounds.Beep.Play();\n}	0
28674249	28674130	Wrong value with TextBox.Text after DatePicker	if(!IsPostback)\n{\n   this.TextBox1.Text = FirstDayOfMonthDateTime.ToString(dd/MM/yyyy);\n   this.TextBox2.Text = LastDayOfPreviousMonthDateTime.ToString(dd/MM/yyyy);\n}	0
4025161	4025125	Is instantiating a Queue using {a,b,c} possible in C#?	var q = new Queue<string>( new[]{ "A", "B", "C" });	0
7739588	7739504	create session in c# to post data in form	class CookieAwareWebClient : WebClient\n{\n    public CookieContainer Cookies { get; private set; }\n\n    public CookieAwareWebClient()\n    {\n        Cookies = new CookieContainer();\n    }\n\n    protected override WebRequest GetWebRequest(Uri address)\n    {\n        var request = base.GetWebRequest(address) as HttpWebRequest;\n        if (request != null)\n        {\n            request.CookieContainer = Cookies;\n            return request;\n        }\n\n        return null;\n    }\n}	0
7786378	7786253	Property Injection for Base Controller Class	builder.RegisterControllers(typeof(MvcApplication).Assembly)\n       .PropertiesAutowired();	0
1598089	1592285	Outline a path with GDI+ in .Net	// Declaration required for interop\n[DllImport(@"gdiplus.dll")]\npublic static extern int GdipWindingModeOutline( HandleRef path, IntPtr matrix, float flatness );\n\nvoid someControl_Paint(object sender, PaintEventArgs e)\n{\n    // Create a path and add some rectangles to it\n    GraphicsPath path = new GraphicsPath();\n    path.AddRectangles(rectangles.ToArray());\n\n    // Create a handle that the unmanaged code requires. nativePath private unfortunately\n    HandleRef handle = new HandleRef(path, (IntPtr)path.GetType().GetField("nativePath", BindingFlags.NonPublic | BindingFlags.Instance).GetValue(path));\n    // Change path so it only contains the outline\n    GdipWindingModeOutline(handle, IntPtr.Zero, 0.25F);\n    using (Pen outlinePen = new Pen(Color.FromArgb(255, Color.Red), 2))\n    {\n        g.DrawPath(outlinePen, path);\n    }\n}	0
10361824	10361809	Format string as currency	NumberFormatInfo info = (NumberFormatInfo)CultureInfo.InvariantCulture.NumberFormat.Clone();\n    info.NumberGroupSeparator = " ";\n\n    Console.WriteLine(12345.ToString("n", info )); // 12 345.00	0
11315780	11315539	Scroll bar doesn't stay within client area in Winforms tab control	private void LoadEditorTab()\n    {\n        var editor = new PcmEditorForm();\n        var grid = new GridView();\n        grid.width=editor.width\n        grid.Anchor= AnchorStyles.Left | AnchorStyles.Top | AnchorStyles.Right;\n        editor.Controls.Add(grid);\n        tabEdit.Controls.Clear();\n        editor.TopLevel = false;\n        editor.Visible = true;\n        editor.dock=DockStyle.Fill;  // Dock the editor\n        tabEdit.Controls.Add(editor);\n    }	0
5224766	5224763	Return null from generic method	default(T)	0
16613450	16613088	How do you write text beyond the boundaries of a textbox without it adding a new line?	textBox1.WordWrap = false;	0
6386752	6386463	Organizing eventlogs into folders	EventLog.CreateEventSource	0
17194770	17194332	Associating a String With a Specific Integer Value	foreach (int T in ToolList)\n{\n   strToolList.add(Enum.GetName(typeof(Tools), (Tools)T)); \n}	0
22806244	22804992	how to get the namespaces in the root of xml	var q = xdoc.Root.Attributes()\n                 .Where(x => x.IsNamespaceDeclaration)\n                 .Select(x => new {Prefixes = x.Name.LocalName, ns = x.Value});	0
1387242	1387236	Show input dialog in WinForms	using (FrmModal myForm = new FrmModal())\n{\n    DialogResult dr = myForm.ShowDialog();\n    if (dr == DialogResult.OK)\n    {\n        // ...\n    }\n    else\n    {\n        // ...\n    }\n}	0
10890610	10890450	Convert utf-8 XML document to utf-16 for inserting into SQL	XDocument xDoc = XDocument.Parse(utf8Xml);	0
17667115	17666942	C# - Download img and converting bytes to bitmap only works with Fiddler open	System.Net.WebRequest request = System.Net.WebRequest.Create(YourURLString);\n      System.Net.WebResponse resp = request.GetResponse();\n      System.IO.Stream respStream = resp.GetResponseStream();\n      Bitmap bmp = new Bitmap(respStream);\n      respStream.Dispose();\n      picturebox1.Image = bmp;	0
1469574	1469518	How can I handle multiple row revisions in a single table?	--  CUSTOMER  ----\nCustomerId\n\n--  QUOTE  ----\nQuoteId\nCustomerId\nData1Id\n\n--  QUOTEREVISION  ----\nQuoteRevisionid\nQuoteId\nCreatedAt\nData2Id\nData3Id\n\n--  DATA1  ----\nData1Id\n\n--  DATA2  ----\nData2Id\n\n--  DATA3  ----\nData3Id	0
20464055	20463799	Ordering Array - C# WPF	var orderedEntries = from entry in entries orderby entry.Length, entry select entry;\n    foreach (var entry in orderedEntries)\n    {\n        // TODO - add to WPF control\n    }	0
7536664	7535863	LINQ aggregating multiple IEnumerables into one?	var dict = ... // dictionary\nvar keys = ... // enumerable with 1 and 3 in it\nvar result = from key in keys\n             from val in dict[key]\n             select val;	0
299228	299209	Dump stored proc output params into a DataGridView row	//set up the datatable\nDataTable dt = new DataTable("parms");\ndt.Columns.Add("ParmName",typeof(string));\ndt.Columns.Add("ParmValue",typeof(string));\n//bind to a gui object\nmyDataGridView.DataSource = dt;\n\n//do this after each sproc call\nforeach (SqlParameter parm in cmd.Parameters)\n{\n    if (parm.Direction == ParameterDirection.Output)\n    {\n        //do something with parm.Value\n        dt.Rows.Add(new object [] { parm.ParameterName, \n            Convert.ToString(parm.Value) } );\n    }\n}	0
2187032	2186794	How can I get correct payperiod from date?	const int DaysInPeriod = 14;\n\nstatic IEnumerable<DateTime> GetPayPeriodsInRange(DateTime start, DateTime end, bool isOdd)\n{\n    var epoch = isOdd ? new DateTime(2009, 11, 1) : new DateTime(2009, 4, 1);\n    var periodsTilStart = Math.Floor(((start - epoch).TotalDays) / DaysInPeriod);\n\n    var next = epoch.AddDays(periodsTilStart * DaysInPeriod);\n\n    if (next < start) next = next.AddDays(DaysInPeriod);\n\n    while (next <= end)\n    {\n        yield return next;\n        next = next.AddDays(DaysInPeriod);\n    }\n\n    yield break;\n}\n\nstatic DateTime GetPayPeriodStartDate(DateTime givenDate, bool isOdd)\n{\n    var candidatePeriods = GetPayPeriodsInRange(givenDate.AddDays(-DaysInPeriod), givenDate.AddDays(DaysInPeriod), isOdd);\n    var period = from p in candidatePeriods where (p <= givenDate) && (givenDate < p.AddDays(DaysInPeriod)) select p;\n    return period.First();\n}	0
30141861	30141584	Windows ComboBox Selected Item (populated from List<>)	dynamic item = cbo.SelectedItem;\n\nString text = item.Text;\nInt32 value = item.Value;	0
7255832	7255755	ConnectionString in LinqToSQL	path = New Uri(Assembly.GetExecutingAssembly().CodeBase).LocalPath;\npath = IO.Path.GetDirectoryName(path);	0
12479204	12426901	Embed an Excel graphic in a Word document with OpenXML working with Word 2010 and 2003	private static void Word2003(ChartPart importedChartPart, MainDocumentPart mainDocumentPart, Stream fileStream)\n{\n    // Add of the external data id\n    ExternalData ext = new ExternalData { Id = "rel" + 5 };\n    AutoUpdate autoUpdate = new AutoUpdate{ Val = false};\n    ext.Append(autoUpdate);\n    importedChartPart.ChartSpace.Append(ext);\n\n    // Set of the relationship\n    var fi = new FileInfo(@"generated.xlsx");\n    importedChartPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/oleObject", new Uri(fi.Name, UriKind.Relative), "rel5");\n\n    // Link to the embedded file\n    EmbeddedPackagePart embeddedObjectPart = mainDocumentPart.AddEmbeddedPackagePart(@"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");\n    Stream copyStream = new MemoryStream();\n    fileStream.CopyTo(copyStream);\n    embeddedObjectPart.FeedData(copyStream);\n}	0
4352088	4343897	Is it possible to select both treeview node and the row of a datagridview	int currRow = 0; currRow = dataGridView1.CurrentRow.Index;\n   dataGridView1.ClearSelection();\n       dataGridView1.Rows[currRow].Selected = true;	0
17242661	17233122	Convert Encode string value to PDF-417 barcode in Windows 8 application?	var writer = new BarcodeWriter\n{\n   Format = BarcodeFormat.PDF_417,\n   Options = new EncodingOptions {Width = 115, Height = 65}\n};\nvar imgBitmap = writer.Write(value);	0
7896547	7896210	How do I find the MAC address of the NetworkInterface that is "IPEnabled"?	For Each tInterface As NetworkInterface in NetworkInterface.GetAllNetworkInterfaces()\n  If (tInterface.Supports(NetworkInterfaceComponent.IPv4)) Or (tInterface.Supports(NetworkInterfaceComponent.IPv6)) Then\n    '\n    '  Do something with tInterface.GetPhysicalAddress()\n    '\n  End If\nNext	0
10242845	10242790	Cannot send mail in SharePoint using Event Receiver	SPWeb thisWeb = thisSite.RootWeb;\nstring toField = "someone@microsoft.com";\nstring subject = "Test Message";\nstring body = "Message sent from SharePoint";\nHttpContext oldContext = HttpContext.Current;\nHttpContext.Current = null;\n\nbool success = SPUtility.SendEmail(thisWeb, true, true, toField, subject, body);\nHttpContext.Current = oldContext;	0
8004574	8003601	C# - Cannot commit changes to Access DB	data.AcceptChanges()	0
19312030	19311204	WinForm Browser Control Which Element was right clicked?	document.activeElement	0
7985803	7985701	How to make a function into a class or module in c#	protected void SendErrorMessageToClient(string strErrorType, string strErrorMessage, Page page)\n{\n    string strMessageToClient = "";\n\n    //Allow single quotes on client-side in JavaScript\n    strErrorMessage = strErrorMessage.Replace("'", "\\'");\n\n    strMessageToClient = "<script type=\"text/javascript\" language=\"javascript\">alert( '" + strErrorType + "\\n\\n" + strErrorMessage + "' );</script>";\n\n    page.ClientScript.RegisterStartupScript(this.GetType(), "ErrorMessage", strMessageToClient);\n\n}	0
13119163	13068734	WPF Prism Load XML in module	Uri uri = new Uri("MainModule1;component/" + resourceFile, UriKind.Relative);	0
6856207	6856024	Combine 2 Datatables with the common rows only	var result = from r in dt.AsEnumerable()\n                     join c in dt2.AsEnumerable()\n                     on r.Field<string>("col1") equals c.Field<string>("col1")\n                     select r;	0
3864003	3856052	C# REST client sending data using POST	request = (HttpWebRequest) WebRequest.Create(uri);\nrequest.PreAuthenticate = true;\nrequest.Credentials = new NetworkCredential(user, password);\nrequest.Method = WebRequestMethods.Http.Post;	0
14537574	14537041	make delayed mousedown event	private Point mouseDownPos;\n\n    private void dataGridView1_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e) {\n        mouseDownPos = e.Location;\n    }\n\n    private void dataGridView1_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e) {\n        if ((e.Button & MouseButtons.Left) == MouseButtons.Left) {\n            if (Math.Abs(e.X - mouseDownPos.X) >= SystemInformation.DoubleClickSize.Width ||\n                Math.Abs(e.Y - mouseDownPos.Y) >= SystemInformation.DoubleClickSize.Height) {\n                // Start dragging\n                //...\n            }\n        }\n    }	0
23902967	23900612	How can I create a localizable UserControl?	Imports System.ComponentModel\n\nPublic Class ctlA\n\n    Private _LabelText As String = "label"\n    <Localizable(True)>\n    Public Property LabelText() As String\n        Get\n            Return _LabelText\n        End Get\n        Set(ByVal value As String)\n            _LabelText = value\n            Label1.Text = value\n        End Set\n    End Property\nEnd Class	0
24256053	24255573	How to get wikipedia content in text box in C#	using System;\nusing System.Collections.Generic;\nusing System.Net;\nusing System.IO;\nusing System.Linq;\nusing Newtonsoft.Json;\n\npublic class Program\n{\n    public static void Main()\n    {\n        WebClient client = new WebClient();\n\n        using (Stream stream = client.OpenRead("http://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&explaintext=1&titles=stack%20overflow"))\n        using (StreamReader reader = new StreamReader(stream))\n        {\n            JsonSerializer ser = new JsonSerializer();\n            Result result = ser.Deserialize<Result>(new JsonTextReader(reader));\n\n            foreach(Page page in result.query.pages.Values)\n                Console.WriteLine(page.extract);\n        }\n    }\n}\n\npublic class Result\n{\n    public Query query { get; set; }\n}\n\npublic class Query\n{\n    public Dictionary<string, Page> pages { get; set; }\n}\n\npublic class Page\n{   \n    public string extract { get; set; }\n}	0
3142718	3142694	Always exclude property from Entity Framework 4 Query	namespace MyCompany.Data.Repositories\n{\n    public class User\n    {\n        public int Id { get; set; }\n        public string Username { get; set; }\n        public string Name { get; set; }\n        public bool Locked { get; private set; }\n    }\n\n    public class UserRepository\n    {\n        public User GetAll() { }\n        public User GetById() { }\n\n        // Add your check password method here\n    }\n}	0
8175171	8175062	WinForms - ComboBox: Find selected item and set index	var data=(List<YourType)myComboBox.DataSource;\nmyComboBox.SelectedIndex=data.FindIndex(p=>p.Text=="SomeValue");	0
1771754	1771741	How to force sub classes to implement a method	public abstract class YourClass\n{\n    // Your class implementation\n\n    public abstract void DoSomething(int x, int y);\n\n    public void DoSomethingElse(int a, string b)\n    {\n        // You can implement this here\n    }\n}	0
17993738	17993309	Export To excel with formatting	workbook.Save(HttpContext.Current.Response, "HelloWorld.xls", ContentDisposition.Attachment, new XlsSaveOptions(SaveFormat.Excel97To2003));	0
6421303	6417775	asp.net/c# ---how to loop checkbox in a div?	int i = 0;\nforeach (Control ctl in myForm.FindControl("myDiv").Controls)\n{\n    if (ctl is CheckBox)\n    {\n        if (((CheckBox)ctl).Checked)\n            i++;\n    }\n}	0
27376953	27376275	WPF determine element is visible on screen	Point locationFromWindow = this.textBox.TransformToVisual(this).Transform(new Point(0, 0)); \nPoint point = this.textBox.PointToScreen(new Point(0, 0));\nRect rect = new Rect(0, 0, SystemParameters.PrimaryScreenWidth, SystemParameters.PrimaryScreenHeight);\nif (!rect.Contains(point))\n{\n    // Outside screen bounds.\n}	0
7109668	7109500	Multiple Trips to the Db	using (SqlConnection...)\n{\n // all your data calls\n}	0
13146835	13146810	C++/Cli add callback to a managed Action<T1,T2> object	Action<string^, string^>^	0
26938608	26938407	Select cells (buttons) on diagonals of a square matrix	var n = (int) Math.Sqrt(pads.Length);\nint i = 0, j = 0, k = 0;\nfor(i = 0; i < n; i++){\n   k = i;\n   AnimatePad(ref beginMs, spd, pads[k], toColor);\n   for(j = 0; j < i; j++){\n      k += n-1;          \n      AnimatePad(ref beginMs, spd, pads[k], toColor);\n   }\n   beginMs += interval;\n}\nfor(i = n-2; i >= 0; i--){       \n   k = (n-i)*n - 1;\n   AnimatePad(ref beginMs, spd, pads[k], toColor);\n   for(j = 0; j < i; j++){\n      k += n-1;\n      AnimatePad(ref beginMs, spd, pads[k], toColor);\n   }\n   beginMs += interval;\n}	0
19986100	19985889	Create a fixed size file in .NET	public override void SetLength(\n    long value\n)	0
22675006	21760847	EF Attach won't update database fields to null	db.Entry(entidade) = EntityState.Modified;\ndb.SaveChanges();	0
13040153	13039699	System Drawing Invert Region build out of Path	private void panel1_Paint(object sender, PaintEventArgs e)\n{\n    GraphicsPath path = new GraphicsPath();\n    path.AddArc(0, 0, (this.Width / 2), (this.Height / 2), 135, 195);\n    path.AddArc((this.Width / 2), 0, (this.Width / 2), (this.Height / 2), 210, 195);\n    path.AddLine((this.Width / 2), this.Height, (this.Width / 2), this.Height);\n\n    GraphicsPath path2 = new GraphicsPath();\n    path2.AddRectangle(new Rectangle(new Point(0, 0), panel1.Size));\n\n    path2.AddPath(path, false);\n\n    e.Graphics.FillPath(Brushes.Black, path2);\n}	0
26729681	26729171	i need help returning the input of an array with the biggest sum	public static int [] threeIntegers (int [] numbers){\n    int max=0 //assuming array contains positive only\n    int [] maxArray = new int [3];\n    for(int j=0;j<numbers.length-2;++j){\n      int sum=0;\n      int [] newArray = new int [3];\n      for(int i=0; i<3;i++){\n        sum+=numbers[i+j];\n        newArray[i]=numbers[i+j];\n      }\n      if (sum>max){\n        max=sum;\n        maxArray=newArray;\n      }\n   }\n\n   return maxArray;\n}	0
23090355	23086462	Create non clustered primary key with fluent nhibernate	public class CustomMsSql2008Dialect : MsSql2008Dialect\n        {\n            public override string PrimaryKeyString\n            {\n                get { return "primary key nonclustered"; }\n            }           \n\n        }	0
7298432	7298424	How to get variable outside loop?	countReader = command7.ExecuteReader();\nstring countName = String.Empty;\n\n while (countReader.Read())\n {\n  countName = countReader["count(*)"].ToString();                \n }	0
25123683	25112420	ServiceStack.Text deserializing an Array with null entries incorrectly	List<List<int>>	0
9146409	9142007	Sub-Select Using LinqToExcel	var credits = from credit in this.test.WorksheetNoHeader().ToList()\n  join debit in this.test.WorksheetNoHeader().ToList() on credit[6] equals debit[6]\n  where debit[13] != "0.00"\n  where debit[13] == credit[15]\n  select credit	0
9873162	9872987	html element press button	webBrowser1.Document.GetElementById("ctl00_ucContent_cntrlRegister_btnRegister").PerformClick();	0
17284088	17284021	Inserting data from ASP.Net form to a datatable	DataTable _table = new DataTable()\nDataRow _row = _table.NewRow()\n_table.Rows.Add(_row)	0
29606769	29606063	Add picture in premade powerpoint presentation	objSlide = objSlides[15]	0
15259002	15258818	Deserialize XML Array Where Root is Array and Elements Dont Follow Conventions	[XmlRoot("TERMS")]\npublic class TermData\n{\n    public TermData()\n     {\n       terms = new List<Term>();\n     }\n\n    [XmlElement("TERM")]\n    public List<Term> terms{get;set;}\n}\n\npublic class Term\n{\n    [XmlElement("ID")]\n    public string id{get;set;}\n\n    [XmlElement("DESC")]\n    public string desc{get;set;}\n}	0
18565455	18564577	Obtain all Child Nodes of Specific Type Returns Nothing	XmlNamespaceManager nsmgr = new XmlNamespaceManager(xdoc.NameTable);\nnsmgr.AddNamespace("x", xdoc.DocumentElement.NamespaceURI);\nXmlNodeList pits = dStr.SelectNodes("x:pit");	0
16856731	16856687	Getting Data from SQL and putting in a list	List<Fruit> fruits = new List<Fruit>();\n\nwhile (reader.Read())\n{\n    Fruit f = new Fruit();\n    f.aID = (string) reader["aID"];\n    f.bID = (string) reader["bID"];\n    f.name = (string) reader["name"];\n    fruits.Add(f);\n}	0
32011897	32011649	How to replace multiple occurrences in single pass?	string[] replaces =  {"123","456","789"};\nRegex regEx = new Regex("abc");\nint index = 0;\nstring result = regEx.Replace(input, delegate(Match match) { return replaces[index];} );	0
26157490	25792265	How to add content to newsletter in Mailjet API v3 using ASP .NET MVC 5	public void NewsLetterHtmlAdd(NewsLetterHtmlAdd newsLetterHtmlAdd)\n    {\n        string url = "https://api.mailjet.com/v3/DATA/NewsLetter/" + newsLetterHtmlAdd.ID + "/HTML/text/html/";\n\n        url.PostToUrl(newsLetterHtmlAdd.Data, "text/html; charset=utf-8",\n              request =>\n              {\n                  request.Credentials = new NetworkCredential(_apiKey, _secretKey);\n                  request.ContentType = "text/html; charset=utf-8";\n              });\n\n    }	0
30290143	30289775	How to calculate difference of date using sql	string total_req = "select count(*) from Request where Date>='" + d2.ToString() + "'";	0
19244005	19239948	How to save image to the database after it is scanned	using(SqlCommand cmd = new SqlCommand("INSERT INTO MyTable (myvarbinarycolumn) VALUES (@myvarbinaryvalue)", conn))\n{\n    cmd.Parameters.Add("@myvarbinaryvalue", SqlDbType.VarBinary, myarray.length).Value = myarray;\n    cmd.ExecuteNonQuery();\n}	0
12814056	12813996	How to get selected index in user control of dropdownlist from C# file	MyUserControl.ItsDropdown.SelectedIndex	0
29202519	29202508	Is there a way to toggle a boolean variablein C#?	locked = !locked;	0
31659092	31658994	json.NET throwing an InvalidCastException deserializing a 2D array	JObject obj = JObject.Parse(json);\ndouble[,] array = obj["array2D"].ToObject<double[,]>();	0
18820341	18820151	How to populate a dataGridView with an array of user generated integers	int[] theData = new int[] { 14, 17, 5, 11, 2 };\ndataGridView1.DataSource = theData.Where(x => x>0).Select((x, index) =>\n    new { RecNo = index + 1, ColumnName = x }).OrderByDescending(x => x.ColumnName).ToList();	0
14308382	14308284	"Date Taken" not showing up in Image PropertyItems while it shows in file details (file properties) in Windows Explorer	Referenced from AbbydonKrafts\n\n// Get the Date Created property \n//System.Drawing.Imaging.PropertyItem propertyItem = image.GetPropertyItem( 0x132 );\nSystem.Drawing.Imaging.PropertyItem propertyItem \n         = image.PropertyItems.FirstOrDefault(i => i.Id == 0x132 ); \nif( propItem != null ) \n{ \n  // Extract the property value as a String. \n  System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding(); \n  string text = encoding.GetString(propertyItem.Value, 0, propertyItem.Len - 1 ); \n\n  // Parse the date and time. \n  System.Globalization.CultureInfo provider = CultureInfo.InvariantCulture; \n  DateTime dateCreated = DateTime.ParseExact( text, "yyyy:MM:d H:m:s", provider ); \n}	0
18006815	18006544	How to use repeater inside the repeater	protected void parentRep_ItemDataBound(object sender, RepeaterItemEventArgs e)\n{\n   if (args.Item.ItemType == ListItemType.Item || args.Item.ItemType == ListItemType.AlternatingItem)\n   {\n        Repeater childRepeater = (Repeater)e.Item.FindControl("childRep");\n        childRepeater.ItemDataBound += new RepeaterItemEventHandler(childRepeater_ItemDataBound);\n        childRepeater.ItemCommand += new RepeaterCommandEventHandler(childRepeater_ItemCommand);\n        childRepeater.DataSource = dt3; //dt3 is the DataTable from your code sample\n        childRepeater.DataBind();\n   }\n}	0
5856889	5856849	path from fileupload	Path.GetFullPath	0
18458446	18458059	Make a LINQ select O(n), selecting just one element	Car selectedCar = cars\n .Where(x => x.Location * direction > location * direction)\n .Aggregate((a, b) => (a.Location * direction < b.Location * direction) ? a : b);	0
15353941	15353717	Newtonsoft Json Parser	dynamic d = JObject.Parse(json);\n//d.founded == "1998"	0
15370101	15369885	Set multipule images to multipule PictureBoxs	PictureBox[] pictureBoxes = { PictureBox1, PictureBox2, PictureBox3, PictureBox4 };\nImage[] images = { ImageHere1, ImageHere2, ImageHere3, ImageHere4 };\n\nfor (int i = 0; i < pictureBoxes.Length; i++)\n{\n    pictureBoxes[i].Image = images[i];\n}	0
11327300	10964070	Auto Refresh Data In Entity Framework	MyModelEntities.Refresh(System.Data.Objects.RefreshMode.StoreWins, TbMyRecord);	0
3047225	3047119	Increment a value from AAA to ZZZ with cyclic rotation	// iterate cyclicly from 0 to 26^3 - 1\nint incrementValue(int i) {\n    // a verbose way of writing "return (i + 1) % 26^3"\n    i++;\n    if (i == 26*26*26) i = 0;\n    return i;\n}\n\n// convert 0 to AAA, 1 to AAB, ...\nstring formatValue(int i) {\n    var result = new StringBuilder();\n\n    result.Insert(0, (char)('A' + (i % 26)));\n    i /= 26;\n    result.Insert(0, (char)('A' + (i % 26)));\n    i /= 26;\n    result.Insert(0, (char)('A' + (i % 26)));\n\n    return result.ToString();\n}	0
13361955	13361745	Get an image from service	return "data:image/jpeg;base64," + Convert.ToBase64String(p.Trunk);	0
1340003	1339976	How to check if any flags of a flag combination are set?	if ((letter & Letters.AB) != 0)\n{\n    // Some flag (A,B or both) is enabled\n}\nelse\n{\n    // None of them are enabled\n}	0
21522708	21522389	Not filling combo box data in all rows of data grid view in windows application	If e.ColumnIndex = 3 Then\n\n\n Dim c As DataGridViewComboBoxColumn\n\n\n    Dim cmd2 As New SqlCommand("select Did,DName from Designation_tbl where deleted=0", con.connect)\n    cmd2.CommandType = CommandType.Text\n    Dim objdataadapter As New SqlDataAdapter(cmd2)\n    Dim results As New DataSet\n\n    objdataadapter.Fill(results, "DesignationMaster_tbl")\n    c = DGVEmployee.Columns(3)\n    c.DataSource = results.Tables("DesignationMaster_tbl")\n    c.ValueMember = "Did"\n    c.DisplayMember = "DName"\n    con.disconnect()\n    end if	0
27304056	27303836	Using the value of trackbar as a variable for another class	private int xSpeed;\nprivate int ySpeedMod; // we have the direction variable here -1 or 1 so everytime you want to change the direction you change this variable\nprivate int ySpeed {\n    get { return Form.trackBarValue * ySpeedMod; }\n}	0
9372086	9372022	How to compare the byte array and byte array list?	using System.Linq;\n\n//...\n\nif (portBuffer.SequenceEqual(ret_bytes))\n         status = 0;	0
5851858	5851833	C# WPF child window (about window)	// Instantiate window\nAboutWindow aboutWindow = new AboutWindow();\n\n// Show window modally\n// NOTE: Returns only when window is closed\nNullable<bool> dialogResult = aboutWindow.ShowDialog();	0
5921915	5921747	Format to POST data with HttpWebRequest	"SetPropertyValue/{propertyID}/{propertyValue}"	0
9784668	9784630	Function with variable number of arguments	void PrintReport(string header, params int[] numbers)\n{\n    Console.WriteLine(header);\n    foreach (int number in numbers)\n        Console.WriteLine(number);\n}	0
18765874	17640055	C# RSACryptoServiceProvider: How to check if a key already exists in container?	public static bool DoesKeyExists(string containerName)\n    {\n        var cspParams = new CspParameters\n        {\n            Flags = CspProviderFlags.UseExistingKey,\n            KeyContainerName = containerName\n        };\n\n        try\n        {\n            var provider = new RSACryptoServiceProvider(cspParams);\n        }\n        catch (Exception e)\n        {\n            return false;\n        }\n        return true;\n    }	0
3818731	3818649	can I convert windows forms based desktop app to silverlight?	System.Windows.Forms	0
33238614	33237707	Formatting string right in xaml	var convertDecimal = Convert.ToDecimal("45,4512")\nconvertDecimal = Math.Round(convertDecimal , 1);	0
7446638	7445831	how to close a running instance of Word document? (C#)	Word.Application app = (Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");\nif (app == null)\n    return true;\n\nforeach (Word.Document d in app.Documents)\n{\n    if (d.FullName.ToLower() == osPath.ToLower())\n    {\n        object saveOption = Word.WdSaveOptions.wdDoNotSaveChanges;\n        object originalFormat = Word.WdOriginalFormat.wdOriginalDocumentFormat;\n        object routeDocument = false;\n        d.Close(ref saveOption, ref originalFormat, ref routeDocument);\n        return true;\n    }\n}\nreturn true;	0
28907306	28907123	passing a result(double type variable) from a method as an element of an array	int[] array = new int[6]; \n    for(int val = 0; val < 6; val++)\n    {\n    if(array[val] > 0)\n    array[val] = 6; \n    }	0
30551774	30551730	Is it possible to provide a decendent class as a formal parameter in an overriden function and still compile	public class ExtendedReportController:BaseReportController\n{\n    public override ReportExecution GetReportExecution(BaseReportModel model)\n    {\n        var castedModel = (ExtendedFromBaseReportModel) model;\n        ReportExecution exec = new ReportExecution();\n        exec.AddOptionalParameter("SomeID1", castedModel.SomeID1);\n        exec.AddOptionalParameter("SomeID2", castedModel.SomeID2);\n        return exec;\n    }\n}	0
9386610	9386558	Trying to get a list of files in a directory by created date using LINQ	private void Form1_Load(object sender, EventArgs e)\n{\n    DateTime LastCreatedDate = Properties.Settings.Default["LastDateTime"].ToDateTime();\n    var filePaths = Directory.GetFiles(@"\\Pontos\completed\", "*_*.csv").Select(p => new {Path = p, Date = System.IO.File.GetLastWriteTime(p)})\n        .OrderBy(x=>x.Date)\n        .Where(x=>x.Date>=LastCreatedDate);\n\n}	0
2421437	2421090	Help with Find() in the BindingSource	//myBindingSource = dataGridView1.DataSource;\nmyBindingSource.Position = myBindingSource.Find("p_Name", textBox1.Text);	0
28303898	28303832	Check if byte has more than one bit set	n & (n - 1) != 0	0
2744830	2742953	Access HTTP POST data in OpenNETCF Padarn	public class Target : Page\n{\n    protected override void Page_Load(object sender, EventArgs e)\n    {\n        Response.Write("<b><u>Request.Form.Keys</u></b><br>");\n\n        Response.Write("<ul>");\n        foreach (var key in Request.Form.AllKeys)\n        {\n            Response.Write(string.Format(\n              "<li>Key: '{0}'    Value: '{1}'", key, Request.Form[key]));\n        }\n        Response.Write("</ul>");\n\n        // flush\n        Response.Flush();\n    }\n}	0
3699564	3697293	How to add ContextMenu in a particular DataGridViewCell? (C# winforms)	private void _dgwMain_MouseDown(object sender, MouseEventArgs e)\n{\n    if (e.Button == MouseButtons.Right)\n    {\n         DataGridView.HitTestInfo info = _dgwMain.HitTest(e.X, e.Y);\n         //now you can use info.RowIndex and info.CellIndex (not sure for porporty          \n         //name) to generate menu you want\n    }\n}	0
6488234	6488201	Binary Search a List of custom data types to match just one field	public class CompareCustomDataType : IComparer<Student> {\n\n  public int Compare(Student x, Student y)\n  {\n    if (x == y)    return 0;\n    if (x == null) return -1;\n    if (y == null) return 1;\n\n    return String.Compare(x.Surname, y.Surname);\n  }\n...\n}	0
32601709	32601453	looping through dynamic data type variable	dynamic data = JsonConvert.DeserializeObject<dynamic>(json_siteResp);\n\n    foreach (dynamic d in data)\n    {\n        var x = d.DoSomeThing;\n    }	0
9529904	9529830	Formatting a double with decimals C#	double.Parse("2140.76", CultureInfo.InvariantCulture)	0
27762399	27754023	Navigate/refresh to page from another class	(Application.Current.RootVisual as PhoneApplicationFrame).Navigate(new Uri("/PivotPage1.xaml",\n            UriKind.Relative));	0
23120160	23107044	GoToStateAction refusing to change state	{Binding ElementName=grid}	0
20591859	20591848	How to CHANGE the location of a rectangle?	face1.Location.X = new_X;\nface1.Location.Y = new_Y;	0
24615759	24615726	RegEx to match everything after first backslash in URL	Console.Write(\n    new Uri(\n     "http://www.TestThis.com/Some-Data/Some-Other-Data/Even-More-Dat"\n    ).PathAndQuery);	0
13637300	13636648	Wait for a void async method	async Task	0
27588626	27588479	How to subscribe to C# GUI event from ProjectA in dll in ProjectB	MainWindow.UserClickedButtonXEvent += ProjectB.ClassB.UserClickedButtonXFunction;	0
27678174	27678011	WPF: Open and Close windows	private void MenuItem_Click(object sender, RoutedEventArgs e)\n    {\n        App.Current.MainWindow = this;\n        Window1 secondWindow = new Window1();\n        secondWindow.ShowDialog();\n    }	0
31834566	31834203	Load a file from another project	string solutiondir = Directory.GetParent(\n    Directory.GetCurrentDirectory()).Parent.FullName;\n// may need to go one directory higher for solution directory\nreturn XDocument.Load(solutiondir + "\" + ProjectBName + "\Mock\myDoc.html");	0
26893805	26893773	C# How to replace multiple chars in string at the same time?	string sr = a.Replace('A', '4').Replace('a', '4');	0
6392535	6392457	How can I color text in a Rich Textbox in C#?	txtRichTextBox.Select(txtRichTextBox.Text.IndexOf("hi"), "hi".Length);\ntxtRichTextBox.SelectionColor = YourColor;\ntxtRichTextBox.SelectionFont = new Font("Times New Roman",FontStyle.Bold);	0
24253484	24253187	Overwrite specific XML node	// The Id of the Alarm to edit\nint idToEdit = 2;\n\n// The new comment for the Alarm\nstring newCommentValue = "Here is a new comment";\n\nXmlDocument doc = new XmlDocument();\ndoc.LoadXml(xml);\n\nXmlNode commentsElement = doc.SelectSingleNode(String.Format("Alarms/Alarm[Id = '{0}']/Comments", idToEdit));\ncommentsElement.InnerText = newCommentValue;\n\ndoc.Save(Console.Out);	0
14154636	14154567	'field' but is used like a 'type'	using System;\nusing PaymentPlanLogic;\nnamespace PaymentPlanStoreLogic\n{\n  public class Class1\n  {\n    Logger myLog = new Logger();\n\n    void YouForgotThisMethod()\n    {\n      myLog.createLog();\n    }\n  }\n}	0
31672764	31672652	C#: I want every letter of a word to begin in a new line	string str = "Hello C#"\nchar[] arr = str.ToCharArray();\n\nforeach (char c in arr)\n{\n    Console.WriteLine(c);\n}	0
22238632	22236491	WCF data service client connect using session	var cookieAwareWebClient= //.... authenticate \n\nvar db = new ServiceReference.MyEntities(new Uri("MyDomain/WcfDataService.svc"));\n\ndb.SendingRequest += ( s,  arg) =>\n{                \n    HttpWebRequest httpRequest = arg.Request as HttpWebRequest;\n    httpRequest.CookieContainer = cookieAwareWebClient.CookieContainer;   // I made that property public                             \n};\n\nvar myUsers = db.Users.ToList();	0
25287606	25286580	Finding href, id and classes of all links in a web page	HtmlDocument doc = new HtmlWeb().Load("http://www.google.com");\n\n IEnumerable<HtmlNode> linkedPages = doc.DocumentNode.Descendants("a");\n foreach (var item in linkedPages)\n {\n    Console.WriteLine("Href : " + item.GetAttributeValue("href", string.Empty) +\n    " id : " + item.GetAttributeValue("id", string.Empty) +\n    " class : " + item.GetAttributeValue("class", string.Empty));\n }	0
15894405	15876681	how to get the substring	string tempVar = test.Substring(0, test.IndexOf(separator[0].ToString()));	0
613775	613700	How to put the build date of application somewhere in the application?	DateTime buildDate = \n   new FileInfo(Assembly.GetExecutingAssembly().Location).LastWriteTime;	0
21485330	21484403	How convert xml string UTF8 to UTF16?	MemoryStream ms = new MemoryStream();\n        XmlWriterSettings xws = new XmlWriterSettings();\n        xws.OmitXmlDeclaration = true;\n        xws.Indent = true;\n        XDocument xDoc = XDocument.Parse(utf8Xml);\n        xDoc.Declaration.Encoding = "utf-16";\n        using (XmlWriter xw = XmlWriter.Create(ms, xws))\n        {\n\n            xDoc.WriteTo(xw);\n        }\n        Encoding ut8 = Encoding.UTF8;\n        Encoding ut116 = Encoding.Unicode;\n        byte[] utf16XmlArray = Encoding.Convert(ut8, ut116, ms.ToArray());\n        var utf16Xml = Encoding.Unicode.GetString(utf16XmlArray);	0
22334121	22334083	Do you need to create a private backing-variable as soon as you have get/set logic?	private int _age;\n\npublic int Age\n{\n    get { return _age; }\n    set\n    {\n        if (_age > 18)\n            _age = value;\n        else\n        {\n            //throw exception, Show message etc \n        }\n    }\n}	0
13446896	13446882	Check if exclusively only these flags set in enumeration	var onlyTheseFlagsSet = (value[0] | value[1]) == input;	0
7478989	7478938	Run Program At Windows StartUp	RegistryKey rkApp = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);\n\nrkApp.SetValue("MyApp", Application.ExecutablePath.ToString());	0
4270760	4270701	Linq or Lambda Expression for returning comma separated values	var result = from cat in Categories\n             where cat.Id == 39\n             select cat.Name + "-" + String.Join(",",\n                 cat.Products.Select(product => product.Name));	0
22814044	22812427	how to get selected drop down list item from grid view in asp.net 3.5	DropDownList ddl = (DropDownList)e.Row.FindControl("DDL_StatusList1");\n            ddl.SelectedValue = DataBinder.Eval(e.Row.DataItem,"status_id").ToString();\n            if (DataBinder.Eval(e.Row.DataItem, "group_id").ToString() != "")\n            {\n            DropDownList ddl1 = (DropDownList)e.Row.FindControl("DDL_GroupList1");\n            ddl1.SelectedValue = DataBinder.Eval(e.Row.DataItem, "group_id").ToString();\n            }	0
21107354	21106843	Remove items from observablecollection<> in foreach loop	static public ObservableCollection<GetDrive> RootDrive = new ObservableCollection<GetDrive>();\n\npublic MainWindow()\n{\n    InitializeComponent();\n\n    foreach (DriveInfo di in DriveInfo.GetDrives())\n    {\n        ObservableCollection<GetDirectory>directories = new ObservableCollection<GetDirectory>();\n        try\n        {\n            foreach (string s in Directory.GetDirectories(di.Name))\n            {\n                directories.Add(new GetDirectory(s));\n            }               \n        }\n        catch (IOException)  //drive is not ready, e.g. DVD drive\n        {\n           // Handle it?\n        }    \n        RootDrive.Add(new GetDrive(di.Name, directories));\n    }\n}	0
34399426	25595094	How to document Azure Mobile Services Backend	/// <summary>\n    /// Creates a new user account.\n    /// </summary>\n    /// <param name="model">Object containing the basic information about the user.</param>\n    /// <returns>User with the basic data and the JWT token.</returns>\n    /// <exception cref="BusinessLogicException">\n    /// Throws business exception if the user that is being created contains invalid data, such as invalid email, username and so on.\n    /// </exception>\n    public async Task<ResponseMessage<UserLogin>> Post(PostUserModel model)\n    {\n        ...\n    }	0
2219702	2219696	How to know if the user is using multiple monitors	if (Screen.AllScreens.Length > 1)\n{\n    // Multiple monitors\n}	0
33611158	33595012	My Asp.Net 5 web api service recieves Posted Json as NULL	[HttpPost]\n    [Route("UpdateRoles")]\n    public AdminAccountGenericResponse UpdateRoles([FromBody]RoleStatusUserModel model)\n    {	0
5586741	5586720	How to extract an instance of ObjectTypeA encapsulted in an general object? - screenshot attached	Product firstNewProduct = (Product) e.NewItems[0];	0
23672775	23666585	Using controls in a LongListSelector	public static DependencyProperty SomeObjectsProperty = DependencyProperty.Register("SomeObjects", typeof(ObservableCollection<Entities>), typeof(ObjectTemplate), new PropertyMetadata(new ObservableCollection<Entities>(), new PropertyChangedCallback(OnSomeObjectsPropertyChanged));\n\nprivate static void OnSomeObjectsPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)\n{\n    (d as ObjectTemplate).UpdateSomeObjects(e.NewValue as SomeObjects);\n}\n\npublic void UpdateSomeObjects(SomeObjects value)\n{\n    if (value != null && value.Count > 0)\n    {\n        foreach (SomeObject eLink in value)\n        {\n            //Add a new control to a wrap panel for each object in the list\n        }\n    }\n}	0
12727835	12716942	Mono / Android Margin Value Discrepancy	CELL_WIDTH = W/7 - M \nCELL_HEIGHT = H/5 - M	0
29969590	29969429	Combining multiple flags of an enum?	V.Speak ("Text", SpeechVoiceSpeakFlags.SVSFlagsAsync | SpeechVoiceSpeakFlags.SVSFIsXML);	0
2303831	2303533	A call to PInvoke function has unbalanced the stack when including a C DLL into C#	[DllImport("LibNonthreaded.dll", CallingConvention = CallingConvention.Cdecl)]\n public static extern void process(int high, int low);	0
26363762	26363708	How to create a date in Javascript / JQuery from day, month and year?	var whateverName = new Date(year, month, day);	0
5251964	5251915	How to convert Object to List<MyClass>?	IList objectList = obj as IList;	0
15698666	15698582	Not able to get value of html textboxes in javascript	var str1 = document.getElementById("<%= amt3.ClientID %>").value;\n        var str2 = document.getElementById("<%= amt4.ClientID %>").value;\n\n        document.getElementById("<%= hf1.ClientID %>").value = str1;\n        document.getElementById("<%= hf2.ClientID %>").value = str2;	0
22861538	22858307	Updating Connection String in DLL from Winforms - Linq to SQL	TPDataContext db = new TPDataContext(connStr);	0
13744538	13744034	Restarting a windows service after a fixed time interval	namespace Mailer\n{\n  public partial class Mailer : ServiceBase\n  {\n    System.Timers.Timer createOrderTimer;\n    public Mailer()\n    {\n      InitializeComponent();\n    }\n\n    protected override void OnStart(string[] args)\n    {\n      createOrderTimer = new System.Timers.Timer();                      \n      createOrderTimer.Elapsed += new  System.Timers.ElapsedEventHandler(sendmail);\n      createOrderTimer.Interval = 900000; // 15 min\n      createOrderTimer.Enabled = true;\n      createOrderTimer.AutoReset = true;                      \n      createOrderTimer.Start();\n    }\n\n    protected void sendmail(object sender, System.Timers.ElapsedEventArgs args)\n    {\n      //code to send email.\n    }\n\n    protected override void OnStop() {  }\n  }\n}	0
18275728	18275145	Search through Tab Control for specific Tab Item based on a String value	tabControl.SelectedItem = tabControl.Items.OfType<TabItem>().SingleOrDefault(n => n.Name == selectedTabItem);	0
30355168	30354882	How to add parameters to WebMatrix Database.Query?	string selectCommand = "sp_getAllUsers(@0, @1)";\n// selectCommand = "Select * From Users Where first_name = @0 AND last_name = @1";\n...\nvar data = DB.Query(selectCommand, "Foo", "Bar");	0
25831182	25831157	Aspose, how to measure a Font?	'Create an instance of Image and load an existing image\nUsing image As Aspose.Imaging.Image = Aspose.Imaging.Image.Load("c://temp//sample.bmp")\n    'Create and initialize an instance of the Graphics class\n    Dim graphics As New Aspose.Imaging.Graphics(image)\n    'Creates an instance of Font\n    Dim font As New Aspose.Imaging.Font("Times New Roman", 16, Aspose.Imaging.FontStyle.Bold)\n\n    'Create an instance of SolidBrush and set its various properties\n    Dim brush As New Aspose.Imaging.Brushes.SolidBrush()\n    brush.Color = Aspose.Imaging.Color.Black\n    brush.Opacity = 100\n\n    'Draw a String using the SolidBrush object and Font, at specific Point\n    graphics.DrawString("Aspose.Imaging for .Net", font, brush, New Aspose.Imaging.PointF(image.Width/2, image.Height/2))\n\n    ' Export to PNG file format using default options.\n    image.Save("out.bmp",New Aspose.Imaging.ImageOptions.PngOptions())\nEnd Using	0
20955142	20954886	Forcing EF 6 to create tables with model first	public class CompanyContext : DbContext\n{\n    public CompanyContext() : base("CompanyDatabase") { }\n\n    public DbSet<Collaborator> Collaborators { get; set; }\n    public DbSet<Department> Departments { get; set; }\n    public DbSet<Manager> Managers { get; set; }\n}	0
5242615	5242605	How to remove all elements from a dictionary?	taggings.Clear();	0
5823950	5823761	Loop through T model properties. Building a search	typeof(T).GetProperties()	0
28986678	28634542	WCF default serializer do not serialize Dictionary<string,object> with null values	[DataContract]\n    [KnownType(typeof(int[]))]\n    [KnownType(typeof(bool[]))]\n    public class CompositeType\n    {\n        [DataMember]\n        public object UsedForKnownTypeSerializationObject;\n\n    [DataMember]\n    public string StringValue\n    {\n        get;\n        set;\n    }\n    [DataMember]\n    public Dictionary<string, object> Parameters\n    {\n        get;\n        set;\n    }\n}	0
16120838	16120753	Get current class at runtime in a static method?	public abstract class AbstractClass\n{\n    protected static void Method<T>() where T : AbstractClass\n    {\n        Type t = typeof (T);\n\n    }\n}\n\npublic class CurrentClass : AbstractClass\n{\n\n    public void DoStuff()\n    {\n        Method<CurrentClass>(); // Here I'm calling it\n    }\n\n}	0
25924136	25923734	How can I retrieve a list of workitems from TFS in C#?	using Microsoft.TeamFoundation.WorkItemTracking.Client;\n\nQuery query = new Query(\n     workItemStore, \n     "select * from issue where System.TeamProject = @project",\n     new Dictionary<string, string>() { { "project", project.Name } }\n);\n\nvar workItemCollection = query.RunQuery();\nforeach(var workItem in workItemCollection) \n{\n   /*Get work item properties you are interested in*/\n   foreach(var field in workItem.Fields)\n   {\n      /*Get field value*/\n      info += String.Format("Field name: {0} Value: {1}\n", field.name, field.Value);\n   }\n}	0
30383114	30349663	Which Data Type is most appropriate for datetime in thrift communication in c++?	struct TimeStamp {\n  1: i16 year\n  2: byte month\n  3: byte day\n  4: byte hour=0\n  5: byte minute=0\n  6: i16 second=0\n  7: double fraction=0\n}	0
26956637	26956025	Convert long into hexadecimal string (like a memory address)	Console.WriteLine(string.Format("{0:X}", 5488461193L));	0
33691996	33691814	Re-Arrange items In a list In C#	int idx = 2;\nreturn items.Skip(idx).Union(items.Take(idx)).ToList();	0
7669259	7669242	c# Directory.GetFiles file structure from app root	string root = Path.GetDirectoryName(Application.ExecutablePath);\nList<string> FullFileList = Directory.GetFiles(root, "*.*", SearchOption.AllDirectories)\n    .Where(name =>\n    { \n        return !(name.EndsWith("dmp") || name.EndsWith("jpg"));\n    })\n    .Select(file => file.Replace(root, "")\n    .ToList();	0
5277016	5276954	Why do a child class need to implement a parents interface to hide one of that parents methods in C#?	var i = (IBaseInterface) (new ChildClass());	0
27548950	27548651	Catching Invalid Input of a Text Box and Using a custom converter	string input = value.ToString().Replace(",", "."), System.Globalization.CultureInfo.InvariantCulture);\ndouble number;\nbool result = Double.TryParse(input , out number);\nif (result)\n{\n    return number;         \n}\nelse\n{\n    return input;\n}	0
9294696	9294665	C# how do you create a method that passes an array as an argument?	private bool DisplayErrorMessages(String[] array1, String[] array2)	0
3772371	3772321	How to prevent inheritance for some methods?	Collection x = new DerivedClass()	0
8743733	8743551	How to get the complete list of followers	var followers = service.ListFollowersOf(user_id);\nwhile (followers.NextCursor != null)\n{\n    followers =  service.ListFollowersOf(user_id, followers.NextCursor);\n}	0
24308248	24307903	How to tell count of non-empty strings in string array	int wordCount = line.Split(new string[] { "|" }, StringSplitOptions.RemoveEmptyEntries).Length;\nstring[] wordsArr = line.Split(new string[] { "|" }, StringSplitOptions.None);	0
25359258	25358871	Cannot add an entity with a key that is already in use update operation	var languages = TextBoxLanguagesKnown.Text.Split('\n');\n\n// Removes deleted languages (first find all language details that are missing from the UI).\nvar deletedLanguages = objUser.LanguageDetails.Where(ld => !languages\n    .Any(l => ld.Language == l.Trim())).ToArray();\nforeach(var deletedLanguage in deletedLanguages)\n{\n    objUser.LanguageDetails.Remove(deletedLanguage);\n    Context.LanguageDetails.DeleteOnSubmit(deletedLanguage);\n}\n\n// Adds new languages (then adds new language details that are not found in the database).\nvar newLanguages = languages.Where(l => !objUser.LanguageDetails\n    .Any(ld => ld.Language == l.Trim())).ToArray();\nforeach (string newLanguage in newLanguages)\n{\n    var languageDetail = new LanguageDetail\n    {\n        Emp_Id = objUser.Emp_Id,\n        Language = newLanguage.Trim()\n    };\n    objUser.LanguageDetails.Add(languageDetail);\n}\n\nContext.SubmitChanges();	0
31790921	31790814	How to convert an irregular JSON to dictionary or object?	public class User\n{\n    public string id { get; set; }\n    public string username { get; set; }\n    public string full_name { get; set; }\n    public string profile_picture { get; set; }\n}\n\npublic class RootObject\n{\n    public string access_token { get; set; }\n    public User user { get; set; }\n}	0
4646016	4645718	enumeration with FlagsAttributes	class CarOptions\n{\n    public SunroofKind Sunroof { get; set; }\n    public SpoilerKind Spoiler { get; set; }\n    public TintedWindowKind TintedWindow { get; set; }\n    // Note that I split this into two enums - the kind of tinted window\n    // (UV-resistant option too maybe?) and color might be different.\n    // This is just an example of how such option composition can be done.\n    public TintedWindowColor TintedWindowColor { get; set; }\n\n    // In this class, you can also implement additional logic, such as\n    // "cannot have spoiler on diesel engine models" and whatever may be required.\n}\n\nenum SunroofKind\n{\n    None,\n    Electrical,\n    Mechanical\n}\n\nenum SpoilerKind\n{\n    None,\n    Standard\n}\n\nenum TintedWindowKind\n{\n    None,\n    Standard\n}\n\nenum TintedWindowColor\n{\n    Black,\n    Blue\n}	0
33479864	33437747	Adding SqlCommand date range parameters to Crystal Report	Dim FObj As CrystalDecisions.CrystalReports.Engine.TextObject = rpt.ReportDefinition.ReportObjects("Text10")\n        FObj.Text = beginDate.ToString	0
31336612	31335039	Interface does not contain a definition for property	public class Service<TEntity> where TEntity : IEntity\n{\n    // other code omitted \n    public virtual void Insert(TEntity entity)\n    {\n        entity.Created = DateTime.Now;\n\n        // other code omitted\n    }\n}	0
20660043	20659540	Setting multiple items as selected by default list picker- multiple selection mode -windows phone	private void interestms_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    if(interestms.SelectedIndex==-1) return;\n\n    //Here may be you get all selected items no need to maintain two array if you get all selected items.\n    var listcommon = (cast as your type)interestms.SelectedItems;\n    interestms.SelectedIndex=-1;\n}	0
16266726	16266678	C# Date Conversion From Euro Time To en-US Time Needed For Date Calculations	DateTime d1 = DateTime.ParseExact(myJames,"dd/MM/yy");	0
11618252	11616606	Set website port with ServerManager class	ServerManager manager = new ServerManager();\nSite site = manager.Sites[siteName];\n\nforeach (XElement bindingNode in bindingsNode.Elements("Binding")) {\n    Binding binding = site.Bindings.CreateElement();\n    binding.BindingInformation = String.Format("{2}:{0}:{1}", bindingNode.Attribute("Port").Value, bindingNode.Value, bindingNode.Attribute("IP").Value);\n    site.Bindings.Add(binding);\n}\n\nmanager.CommitChanges();	0
23408065	23408027	How to update DateTime value without pressing on it in WF?	private void Window_Loaded(object sender, RoutedEventArgs e)\n{    \n    DispatcherTimer dispatcherTimer = new DispatcherTimer();\n    dispatcherTimer.Tick += new EventHandler(dispatcherTimer_Tick);\n    dispatcherTimer.Interval = new TimeSpan(0, 0, 1);\n    dispatcherTimer.Start();\n}\n\nprivate void dispatcherTimer_Tick(object sender, EventArgs e)\n{\n    this.label17.Text=(DateTime.Now.Hour.ToString() + ":" +\n    DateTime.Now.Second.ToString());    \n}	0
18215930	18214812	How to display form variables based on variable name	string str = "";\nforeach (string item in list)\n{\n    TextBox txt = (TextBox)Form.FindControl(item);\n    if (txt != null)\n    {\n        str += item+":"+ txt.Text+"<br>";\n    }\n}\nResponse.Write(str);	0
2931311	2931302	Using Dispose on a Singleton to Cleanup Resources	~YourClass	0
24697276	24456318	Setting Word CustomTaskPane Width Dynamically	Microsoft.Office.Interop.Word.Application appVersion = new Microsoft.Office.Interop.Word.Application();	0
25363991	25353884	Redirect to another page in different project of same solution	NavigationService.Navigate(new Uri("/TargetProjectName;/TargetPage.xaml", UriKind.Relative));	0
18980441	18980371	how to add the string AppendFormat dynamically in c#	var s = new StringBuilder();\n        s.AppendFormat("\"{0}\",\"{1}",\n                            "test1",\n                            "test2"\n                                     );\n        for (var i = 2; i < 10; i++)\n        {\n            s.AppendFormat(",\"{0}\"", "loop"); \n        }	0
19210470	19210325	How to add formula on Crystal report fields	From the drop down above select Basic Syntax.\n\nIf {TableName.FeeUnit} = {TableName.Percent} Then // Assuming you have FeeUni and Percent as column in TableName table. Drag drop the two and wrap with the code\n    formula=({TableName.Fee}/100)*{TableName.Patients}  // formula here is a keyword\n\nElse \n    formula={TableName.Fee}*{TableName.Patients}  \nEnd If	0
12776080	12760758	convert custom collection to DataRow	var xpCollection = new XPCollection<Person>();\ngridControl1.DataSource = xpCollection;\n//...\nPerson person = (Person)gridView1.GetRow(rowHandle);	0
9515836	9515476	pop up panel from codebehind on button click event	Button1.Attributes.Add( "onclick", "javascript:window.open('http://www.google.com');" );	0
9614654	9614561	How to use CACLS in c# windows service	StreamWriter myStreamWriter = myProcess.StandardInput;\nmyStreamWriter.Writeline("Y"); // Could it be localized ??? -->Oui, Ja, S?? etc...\nmyStreamWriter.Close();  // This seems to be is important.....	0
32963840	32963795	Making Foreach Async	List<object> Response= new List<object>();\n// You need to put some stuff on Response\nParallel.ForEach(Response, o =>\n{\n   Response.Add(callMethod());\n});	0
5266844	5266789	String representation in c#	client.Encoding = System.Text.Encoding.UTF8;	0
15466065	15465383	Trouble Parsing XML	var data =\n    XDocument.Parse(xml)\n    .Root\n    .Element("response")\n    .Element("data")\n    .Elements("row")\n    .Select(row =>\n        new\n        {\n            Id = Int32.Parse(row.Element("id").Value),\n            Parameters = new\n            {\n                IpAddress = row.Element("parameters").Element("ipaddress").Value,\n                port = Int32.Parse(row.Element("parameters").Element("port").Value),\n            },\n            Status = new\n            {\n                MemFree = Int32.Parse(row.Element("status").Element("memfree").Value),\n            },\n        });	0
13826336	13826263	How to skip lines in a text file if ID number is duplicated?	file = file.Where(line => line.Contains("\t"))\n           .GroupBy(line => line.Substring(0, line.IndexOf('\t')))\n           .Where(g => g.Count() == 1)\n           .Select(g => g.First())\n           .ToArray();	0
5835870	5835379	How to make Silverlight Dataform EditTemplate show controls based on checkbox state?	CheckBox.IsChecked	0
24371520	24371440	How to run a method after a specific time interval?	Task.Factory.StartNew(() =>\n    {\n        System.Threading.Thread.Sleep(Interval);\n        TheMethod();\n    });	0
20025640	20024804	Dropdownlist with sqldatareader	ddlStateLegalRes.Items.FindByValue(sdr["STATEOFLEGALRESIDENCE"].ToString()).Selected = true;	0
14062590	14055309	Custom robot filtering in NCrawler	builder.Register((c, p) => new CustomRobotService(p.TypedAs<Uri>(), c.Resolve<IWebDownloader>())).As<IRobot>().InstancePerDependency();	0
8299675	8299633	Merge values from two mutually exclusive DataSets' into a separate DataSet	DataSet a = // Some Pre-filled DataSet.\nDataSet b = // Some Other Pre-filled DataSet.\n\nDataSet c = a.Copy();\nc.Merge(b);	0
12267403	12221950	How to deserialize object that can be an array or a dictionary with Newtonsoft?	public Dictionary<int, Variation> Variations\n    {\n        get\n        {\n            var json = this.VariationsJson.ToString();\n            if (json.RemoveWhiteSpace() == EmptyJsonArray)\n            {\n                return new Dictionary<int, Variation>();\n            }\n            else\n            {\n                return JsonConvert.DeserializeObject<Dictionary<int, Variation>>(json);\n            }\n        }\n    }\n\n    [JsonProperty(PropertyName = "variations")]\n    public object VariationsJson { get; set; }	0
21847056	21846621	Locate up until quotes regex	string regex = @"(http://www\.foo\.com(?:\\.|[^""\\])*)"	0
25680465	25659509	Creating comma separated string from numeric values with multiple formats	var resultString = String.Join(",", new []\n{\n    aLength.ToString("F1"),\n    anAngle.ToString("F4"),\n    aHeight.ToString("F1"),\n    a2DPoint.X.ToString("F2"),\n    a2DPoint.Y.ToString("F2"),\n    anID.ToString(),\n    anInt.ToString(),\n    anotherInt.ToString(),\n}.Concat(aListOfInt.Select(x => x.ToString())));	0
5180619	5180566	C# Fast way to find value in a jagged Array	Dictionary<int, int[]>	0
8325424	8324994	FindControl - can't find dropdownlist	ContentPlaceHolder MainContent = Page.Master.FindControl("MainContent") as ContentPlaceHolder;\n DropDownList myControl1 = (DropDownList)MainContent.FindControl("ddlGoalKeeper");	0
8247516	8242852	Parameterless constructor for serialisation in combination with constructor who has default parameter, why does it work?	new TestClass()	0
34382970	34382088	EF6 unique constraint on foreign key	var author = _ctx.Authors.SqlQuery(\n    "with data as (select @author as [name]) " +\n    "merge Authors a " +\n    "using data s on s.[name] = a.[name] " +\n    "when not matched by target " +\n    "then insert([name]) values(s.[name]); select * from Authors where [name]=@author", new SqlParameter("author", command.Author)).Single();\n\n\nvar book = new Book\n{\n    Isbn = command.Id,\n    Title = command.Title,\n    Stock = command.Count,\n    Author = author\n};\n\n_ctx.Books.Add(book);\n\nawait _ctx.SaveChangesAsync();	0
21153717	21102227	How to prevent Excel from doubling apostrophes?	strCellData = strCellData.Replace("'", "&#39;");	0
17831061	17831011	How to initialize IEnumerable<Object> that be empty and allow to Concat to it?	IEnumerable<Book> books = new List<Book>();	0
11995900	11995669	Appending data to existing xml file	public static void SavePersons(List<Person> Persons, String path)\n{\n//your code\n}	0
22305812	22305567	Robocopy Success/Failure reported via Window's application	Process myProcess = null;\n\n// Start the process.\nmyProcess = Process.Start("robocopy ....");\n\nmyProcess.WaitForExit(1000);\n\nConsole.WriteLine("Process exit code: {0}",  myProcess.ExitCode);	0
18044910	18044863	XML serialize without overwriting	List<Actor>	0
14761274	14761202	mvc4 custom membership provider using nhibernate	System.Web.Security.FormsAuthentication	0
866574	866444	Projector Control/Display C#	System.Windows.Forms.Screen.AllScreens	0
10150585	10150530	Trying to send mail in C# but it doesn't seem to be working	sc.Credentials = netCred;\n\ntry \n{\n  sc.Send(message);\n}  \ncatch (Exception ex) \n{\n  MessageBox(ex.ToString());              \n}              \nMessageBox.Show("Test");	0
6231246	6230635	How to programmaticaly get the AutoRecover Path of a Workbook?	Application.AutoRecover.Path	0
8726312	8726165	Array co-variance in C# generic list	abstract class AnimalProcessor<T> where T : Animal {\n    public abstract IList<T> ProcessResults();\n}\n\nclass GiraffeProcessor : AnimalProcessor<Giraffe> {\n    public override IList<Giraffe> ProcessResults() {\n        return new List<Giraffe>();\n    }\n}\n\nclass LionProcessor : AnimalProcessor<Lion> {\n    public override IList<Lion> ProcessResults() {\n        return new List<Lion>();\n    }\n}	0
13367606	13367592	How To Have a Console Application Create a New Mail Message in Outlook	Process.Start("mailto:a@example.com,b@example.com");	0
12617407	12617297	Resize drawn rectangle to fit original image	selectedWidth * 5606/1058.4	0
5766440	5766418	how to add, edit, delete and queries since other computer (with internet)	public SqlConnection Conectar(string remoteMachine)\n{\n      SqlConnection con = new SqlConnection(string.Format(@"Data Source={0}\sqlexpress;Initial Catalog=misnotas;Integrated Security=True", remoteMachine));\n      return con;\n}	0
29263836	29263662	Regex with a backslash as a pattern terminator	string unc_server_name = new Uri(@"\\JJ01G3C5-10A6S0\C$\2015\Mar\24\").Host;	0
28306118	28305989	How to make a JOIN in LINQ to SQL equivalent to Not Equals	from c in accounts\nfrom p in accounts\nwhere c.Account != p.Account	0
11577374	11577267	How to inform a UserControl that an event has occurred in another UserControl?	var search = new SearchBox();\n var cust = new CustomerList();\n search.SearchSubmitted += (s,e)=>{ cust.Update(e.Term); }	0
31039530	31039319	set font with ColumnText	BaseFont title = BaseFont.CreateFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, BaseFont.EMBEDDED);\nFont titleFont = new Font(title, 10, Font.BOLD, Color.BLACK);\np = new Paragraph(text, titleFont);	0
4825174	4825145	using http response how to save the pdf files	using (var wc = new System.Net.WebClient())\n{\n    wc.DownloadFile(Url, FileName);\n}	0
1506986	1506982	C# LINQ query to select only first date in a month from List<DateTime>	var firstDays = dates.Where(d=> d.Day == 1);	0
4905275	4905215	Does a single NetworkCredential instance apply to only a single URI	// NetworkCredential stores authentication to a single internet resource\n       // supplies credentials in password-based authentication schemes such as basic, digest, NTLM, and Kerberos. \n       NetworkCredential networkCredential = new NetworkCredential("username", "password");\n\n        WebRequest webRequest = HttpWebRequest.Create("www.foobar.com");\n        webRequest.Credentials = networkCredential;\n\n        // to use the same credential for multiple internet resources...\n        CredentialCache credentialCache = new CredentialCache();\n        credentialCache.Add(new Uri("www.foobar.com"), "Basic", networkCredential);\n        credentialCache.Add(new Uri("www.example.com"), "Digest", networkCredential);\n\n        // now based on the uri and the authetication, GetCredential method would return the \n        // appropriate credentials\n        webRequest.Credentials = credentialCache;	0
237278	237275	How can I find all the public fields of an object in C#?	foreach (Object obj in list) {\n    Type type = obj.GetType();\n\n    foreach (var f in type.GetFields().Where(f => f.IsPublic)) {\n        Console.WriteLine(\n            String.Format("Name: {0} Value: {1}", f.Name, f.GetValue(obj));\n    }   \n}	0
4952925	4952890	help in running a command line in a web form	process1.StartInfo.Arguments = "antc";	0
18795864	18795798	How can I create an Expression tree that compares properties in a child object?	var child = Expression.Property(parameter, "Child");\nvar jobNumber = Expression.Property(child, propertyName);\n\nvar lambda =\n    Expression.Lambda<Func<ParentObject, bool>>(\n        comparisonMethod(jobNumber, Expression.Constant(propertyValue)),\n        parameter);	0
28245333	23912484	Windows Service changes behavior of echo / stream redirection in batch file	empty.txt	0
34280769	34279695	Updating Specific column by pressing Update Button C# with Access	using (var cmd = new OleDbCommand("Update staff set username = @username where id = @userid", myConnection))\n   {\n      cmd.Parameters.AddWithValue("@username", txt_name.Text);\n      cmd.Parameters.AddWithValue("@userid", txt_id.Text);\n      cmd.ExecuteNonQuery();\n   }	0
31901922	31901829	BackgroundWorker in C# runs multiple times	Console.WriteLine("BackGroundWork 1 Started");	0
14306106	14305785	Displaying dataview information	private void btnSearchByGender_Click(object sender, EventArgs e)\n{\n    DataView data = new DataView(pID2dbDataSet.customer);\n\n    string gender;\n    if (rdoMale.Checked)\n        gender = "Male"\n    else\n       gender = "Female"\n    data.RowFilter = "Gender = '" + gender + "'";\n    customerDataGridView.DataSource = data;\n}	0
10557511	10556025	Can C# block internet access on a remote Windows PC	Group Policy	0
9186838	9186779	Limit the type of a base class parameter	foreach (var control in controls)\n    Debug.Assert((control is TextBox) || (control is ComboBox));	0
6097717	6097695	Constraint syntax with generics, also deriving from a class	public abstract class DrilldownBase<W> : IDrilldown where W : class,	0
26706011	26705659	How to map a 3D array to a linear array?	public static int[] ToBuffer(int[, ,] buffer3D, int w, int h) {\n    int[] buffer = new int[w * h * 1];\n    Buffer.BlockCopy(buffer3D, 0, buffer, 0, w * h * sizeof(int));\n    return buffer;\n}	0
32752572	32745888	AutoTyper with Multiline TextBox	SendKeys.Send(...)\nawait Task.Delay(10000)\nSendKeys.Send(...)\nawait Task.Delay(10000)	0
5532455	5532394	C# Serialize specific property of nested object	public class Appointment\n    {\n        [XmlIgnore()]\n        public Person MyPerson\n        {\n            get;\n            set;\n        }\n\n        public int MyPersonId\n        {\n            get { return MyPerson.Id; }\n            set { MyPerson = new Person(value)}\n        }\n    }	0
11887209	11879544	How to convert an Unmanaged Image to a managed bitmap image?	BlobCounterBase bc = new BlobCounter();\n                    bc.FilterBlobs = true;\n                    bc.MinHeight = 5;\n                    bc.MinWidth = 5;\n\n                    bc.ProcessImage(numberplate);\n                    Blob[] blobs = bc.GetObjectsInformation();\n                    MessageBox.Show(bc.ObjectsCount.ToString());\n                    for (int i = 0, n = blobs.Length; i < n; i++)\n                    {\n                        if (blobs.Length > 0)\n                        {\n\n                            bc.ExtractBlobsImage(numberplate, blobs[i], true);\n\n                            Bitmap copy = blobs[i].Image.ToManagedImage();\n                            pictureBox2.Image = numberplate;\n                            pictureBox2.Refresh();\n                        }\n                    }	0
11516670	11516617	How to create Xml file in memory to upload on the server	string xml = myXmlElement.OuterXml;\nbyte[] bytes = Encoding.UTF8.GetBytes(xml);\nStream requestStream = request.GetRequestStream();\nrequestStream.Write(bytes, 0, bytes.Length);\nrequestStream.Close();	0
28198751	28198368	How to create a dialog for use by an Excel AddIn?	const string message =\n    "Are you sure that you would like to close the form?";\nconst string caption = "Form Closing";\nvar result = MessageBox.Show(message, caption,\n                             MessageBoxButtons.YesNo,\n                             MessageBoxIcon.Question);\n\n// If the no button was pressed ... \nif (result == DialogResult.No)\n{\n    // cancel the closure of the form.\n    e.Cancel = true;\n}	0
12396712	12396510	Print a star (*) right triangle in C#	int x = 1;\nint j = 10;\nint k = 0;\nwhile (j > 0)\n{\n    if (k <= j)\n    {\n       Console.Write("* ");\n    }\n    if (j >= 1)\n    {\n        int temp = x;\n        while (temp >= 0)\n        {\n            Console.Write(" ");\n            temp--;\n        }\n        x = x + 1;\n        Console.Write("*");\n\n     }\n       Console.WriteLine();\n       j--;\n   }\n   Console.WriteLine();\n   double f = Math.Round(x * 1.5);\n   while (f != 0)\n   {\n      Console.Write("*");\n      f--;\n   }	0
5168673	5168612	Launch Program with Parameters	ProcessStartInfo startInfo = new ProcessStartInfo();        \nstartInfo.FileName = @"C:\etc\Program Files\ProgramFolder\Program.exe";\nstartInfo.Arguments = @"C:\etc\desktop\file.spp C:\etc\desktop\file.txt";\nProcess.Start(startInfo);	0
9403534	9403377	How to serialize a POCO with desired property names	public class job\n{\n    public string title { get; set; }\n    public string company { get; set; }\n    public string companywebsite { get; set; }\n    [XmlArray("locations")]\n    [XmlArrayItem("location")]\n    public string[] locations { get; set; }\n}	0
20849873	20714423	How to inherit a class?	public class ItemEx : Item\n{\npublic byte[] IconData\n    {\n        get { return icon; }\n        set \n        { \n            icon = value;\n            Icon = null;\n        }\n    }\n    public ImageSource Icon\n    {\n        get { return ToImageSource(IconData); }\n        set { RaisePropertyChanged("Icon"); }\n    }\n}\n\npublic static ImageSource ToImageSource(byte[] icon)\n    {\n        if (icon != null)\n        {\n            BitmapImage biImg = new BitmapImage();\n            MemoryStream ms = new MemoryStream(icon);\n            biImg.BeginInit();\n            biImg.StreamSource = ms;\n            biImg.EndInit();\n            return biImg;\n        }\n        return null;\n    }	0
34476660	34476616	How to restrain input to options/strings?	if(s!= "Old" && s!= "New" )\n//send error messeage	0
26048628	26023861	Verify app invite server-side	public static bool CheckInvite(string fromId, string toId)\n    {\n        var fb = new FacebookClient(APP_ID + "|" + SECRET_ID);\n        fb.AppId = APP_ID;\n        fb.AppSecret = SECRET_ID;\n        dynamic result = fb.Get(string.Format("/{0}/apprequests", toId));\n        foreach (var el in result.data)\n            if ((string)el.from.id == fromId)\n            {\n                DateTime dateTime = DateTime.Parse((string)el.created_time, CultureInfo.InvariantCulture);\n                if ((DateTime.Now - dateTime).TotalMinutes < 15)\n                {\n                        return true;\n                }\n            }\n\n        return false;\n    }	0
1805855	1805784	Formatting a text file, how to update the file after I finished parsing it?	string inputFile = Path.Combine(Environment.GetFolderPath(\n        Environment.SpecialFolder.MyDocuments), "temp.txt");\nstring outputFile = Path.Combine(Environment.GetFolderPath(\n        Environment.SpecialFolder.MyDocuments), "temp2.txt");\nusing (StreamReader input = File.OpenText(inputFile))\nusing (Stream output = File.OpenWrite(outputFile))\nusing (StreamWriter writer = new StreamWriter(output))\n{\n    while (!input.EndOfStream)\n    {\n        // read line\n        string line = input.ReadLine();\n        // process line in some way\n\n        // write the file to temp file\n        writer.WriteLine(line);\n    }\n}\nFile.Delete(inputFile); // delete original file\nFile.Move(outputFile, inputFile); // rename temp file to original file name	0
23529043	23528996	List of TimeSpan to String Array using LINQ	var timesAsString = times.Select(s => s.ToString("mm.ss")).ToArray()	0
25107458	25107368	Detect app first launch windows phone	const string settingsAppLaunched = "appLaunched";\n\npublic static bool IsFirstLaunch(){\n    IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;\n    return !(settings.Contains(settingsAppLaunched) && settings[settingsAppLaunched]);\n}\n\npublic static bool Launched(){\n    if(IsFirstLaunch()){\n        IsolatedStorageSettings settings = IsolatedStorageSettings.ApplicationSettings;\n        settings.Add(settingsAppLaunched, true);\n        settings.Save();\n    }\n}\n\n//usage:\nif(IsFirstLaunch()){\n    showTheFrameToTheGuyBecauseHeLaunchedTheAppForTheFirstTime();\n    Launched();\n}	0
6691409	6691215	HttpModule to catch all extensions	aspnet_isapi.dll	0
7006423	7006403	change picture in master page	Image First = new Image(); \n        First = (Image)(Page.Master.FindControl("First"));\n        if (First != null)\n        {\n            First.ImageUrl = "image-path";\n        }	0
15722653	15722155	Weird behavior with lists with a derived generic type	foreach (tDerived<T> lGen in myList.OfType<tDerived<T>>())\n{\n    Console.WriteLine("tDerived found!");\n}\n\nforeach (aDerived lDerived in myList.OfType<aDerived>())\n{\n    Console.WriteLine("aDerived found!");\n}	0
17912959	17912780	C# New window focus	private void display_SelectionChanged(object sender, SelectionChangedEventArgs e) {\n    Dispatcher.BeginInvoke(new Action(() => {\n       var editwindow = new EditWindow();\n       editwindow.Show();\n    }));\n}	0
13348039	13347752	Insert file into google drive with Web request	Content-Type: Application/octet-stream\n Content-Description: The fixed length records\n Content-Transfer-Encoding: base64\n Content-ID: <950120.aaCB@XIson.com>\n\n T2xkIE1hY0RvbmFsZCBoYWQgYSBmYXJtCkUgSS\n BFIEkgTwpBbmQgb24gaGlzIGZhcm0gaGUgaGFk\n IHNvbWUgZHVja3MKRSBJIEUgSSBPCldpdGggYS\n BxdWFjayBxdWFjayBoZXJlLAphIHF1YWNrIHF1\n YWNrIHRoZXJlLApldmVyeSB3aGVyZSBhIHF1YW\n NrIHF1YWNrCkUgSSBFIEkgTwo=	0
4465166	4465016	Exporting from a dataset to a tab delimited file	var builder = new StringBuilder()\n\nforeach(var row in dataSet.Tables.First().Rows)\n{\n   foreach(var cell in row.ItemArray)\n   {\n      builder.Append(cell.ToString());\n      if(cell != row.Cells.Last())\n         builder.Append("\t");\n   }\n   builder.Append(Environment.NewLine);\n}\n\nvar file = new FileStream(filePath);\nvar writer = new StreamWriter(file);\nwriter.Write(builder.ToString());\nwriter.Flush();\nwriter.Close();	0
15429969	15429753	Aggregate duplicate members of an object in C# using LINQ / Lambda	from c in allCompanies\n group c by c.Company into departments\n select new {\n    Company = departments.Key,\n    Departments = from d in departments\n                  group d by d.Department into employees\n                  select new {\n                      Department = employees.Key,\n                      Employees = employees.Select(e => e.Employees)\n                                           .Distinct()\n                  }\n }	0
12327945	12327894	C# fileName display with spaces trouble	string filename = reportName + ".xls";\n Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");	0
9334308	9334100	Process to call Fortran executable from C#	Process exeProcess = new Process();\nexeProcess.StartInfo.FileName = @"...\marcus12.exe";\nexeProcess.StartInfo.UseShellExecute = false;\nexeProcess.StartInfo.RedirectStandardError = true;\nexeProcess.StartInfo.RedirectStandardInput = true;\nexeProcess.StartInfo.RedirectStandardOutput = true;\nexeProcess.Start();\nexeProcess.StandardInput.WriteLine(Path.GetFileName(filePath));\nexeProcess.StandardInput.WriteLine("Y");\nexeProcess.WaitForExit();	0
29577734	29577284	How to send log in credentials and receive a html page in C# using a Windows Phone 8/8.1 app?	public async Task<string> httpPOST(string url, FormUrlEncodedContent content)\n{\n    var httpClient = new HttpClient(new HttpClientHandler());\n    string resp = "";\n    HttpResponseMessage response = new HttpResponseMessage();\n\n    response = await httpClient.PostAsync(url, content);\n\n    try\n    {\n        response.EnsureSuccessStatusCode();\n\n        Task<string> getStringAsync = response.Content.ReadAsStringAsync();\n\n        resp = await getStringAsync;\n    }\n    catch (HttpRequestException)\n    {\n        resp = "NO_INTERNET";\n    }\n\n        return resp;\n}	0
209219	209160	Nullable type as a generic parameter possible?	static void Main(string[] args)\n{\n    int? i = GetValueOrNull<int>(null, string.Empty);\n}\n\n\npublic static Nullable<T> GetValueOrNull<T>(DbDataRecord reader, string columnName) where T : struct\n{\n    object columnValue = reader[columnName];\n\n    if (!(columnValue is DBNull))\n    return (T)columnValue;\n\n    return null;\n}	0
30475988	30475836	How to loop through the properties of a Class?	object obj = new object();\nPropertyInfo[] properties = obj.GetType().GetProperties();\nforeach (var p in properties)\n{\n    var myVal = p.GetValue(obj);\n}	0
1861893	1861813	format string email to email-link	public string emailLink(string emailAddress)\n{\n    Regex emailRegex = new Regex(@"^(?!.*\.\.)[a-zA-Z0-9\w\._%&!'*=?^+-]*@[a-zA-Z0-9][\w\.-]*[a-zA-Z0-9]*\.[a-zA-Z][a-zA-Z\.]*[a-zA-Z]$";\n\n    if (emailRegex.IsMatch(emailAddress)\n    {\n        return string.Format("<a href=\"mailto:{0}\">{0}</a>", emailAddress);\n    }\n    return "";\n}	0
20362744	20340045	Custom json contractresolver .net web api falling back to camelcase in some cases	public class MyCustomResolver : CamelCasePropertyNamesContractResolver\n{\n    protected override string ResolvePropertyName(string propertyName)\n    {\n        return propertyName == "Links" ? "_links" : base.ResolvePropertyName(propertyName);\n    }\n}	0
31843846	31843285	How to get all form fields in a winforms app as one parameter?	private void btnSubmit_Click(object sender, EventArgs e) {\n    var formFields = **formFieldCollection**;\n\n    var firstName = MyUserControl.FirstName.Text;\n    var lastName = MyUserControl.LastName.Text;\n}	0
21617639	21617530	How can I tell if a phone is connected by wifi or has access to mobile internet via C#?	public static string GetNetStates()\n{\n    var info = Microsoft.Phone.Net.NetworkInformation.NetworkInterface.NetworkInterfaceType;\n    switch (info)\n    {\n        case NetworkInterfaceType.MobileBroadbandCdma:\n            return "CDMA";\n        case NetworkInterfaceType.MobileBroadbandGsm:\n            return "CSM";\n        case NetworkInterfaceType.Wireless80211:\n            return "WiFi";\n        case NetworkInterfaceType.Ethernet:\n            return "Ethernet";\n        case NetworkInterfaceType.None:\n            return "None";\n        default:\n            return "Other";\n    }   \n}	0
10500488	10500441	Which class should I use to write binary data to a buffer (say a List of bytes)	using (var myStream = new MemoryStream()) {\n    using (var myWriter = new BinaryWriter(myStream)) {\n        // write here\n    }\n    using (var myReader = new BinaryReader(myStream)) {\n        // read here\n    }\n\n    // put the bytes into an array...\n    var myBuffer = myStream.ToArray();\n\n    // if you *really* want a List<Byte> (you probably don't- see my comment)\n    var myBytesList = myStream.ToArray().ToList();\n}	0
25896667	25896587	Objects don't seem to get saved into database	dbContext.Exams.Include(e => e.Questions)	0
23777247	23776320	Automatic merge of objects referenced from another collection	public Wsp GetFullWsp(Guid id)\n{\n    var wsp = wspCollection.AsQueryable().FirstOrDefault(w => w.WspId == id);\n    var sits = sitCollection.AsQueryable().Where(sit => sit.WspId == id);\n    wsp.SitList = new List<Sit>(sits);\n}	0
6781836	6781418	Using Ninject to fill Log4Net Dependency	context.Request.ParentRequest.ParentRequest.Target.Member.DeclaringType	0
9081566	9081472	How use single Log4net configuration (separate file or inside app.config) for all my project?	Properties -> Copy to output folder -> Copy Always	0
22012530	22012377	Web API routing with parameter	[HttpGet]\n    public List<Category> FunctionWithParam(long id)\n    {\n        //return something\n    }	0
14581995	14581659	How can I take a sample still image from two pictureBoxes in fullscreen every X seconds?	int sequence = 0;\n\nprivate void timer1_Tick(object sender, EventArgs e)\n{\n    using(var still = new Bitmap(form.Width, form.Height))\n    {\n        form.DrawToBitmap(still, new Rectangle(new Point(0, 0), still.Size));\n        still.Save(String.Format(@"c:\still_{0}.gif", sequence++), ImageFormat.Gif);\n    }\n}	0
4434043	4434014	How to add xml:lang="en" to <html> tag	XAttribute xmlLang = new XAttribute(XNamespace.Xml + "lang", "en");	0
30476632	30476230	DateTime Format user entries	var testString = "2Y 4M 3D";\n        var splitString = testString.Split(' ');\n        var year = int.Parse(splitString[0][0].ToString(CultureInfo.InvariantCulture));\n        var month = int.Parse(splitString[1][0].ToString(CultureInfo.InvariantCulture));\n        var day = int.Parse(splitString[2][0].ToString(CultureInfo.InvariantCulture));\n        var totalSeconds = (DateTime.Now.AddYears(year).AddMonths(month).AddDays(day) - DateTime.Now).TotalSeconds;	0
27020686	26999144	How to convert a list of objects to a list of strings in c#?	foreach (DataRow dr in dt.Rows)\n{\n    lstweeks.Add(\n    {\n         new GetData{week = dr["WK"].ToString()}\n    );\n}	0
1827554	1827281	How to create and manage several datasets	dim ds as new dataset	0
1266999	1266382	How to get a list of all users in SharePoint	SPGroupCollection collGroups = SPContext.Current.Web.Groups;\n\n foreach (SPGroup oGroup in collGroups)\n                {\n                    foreach (SPUser oUser in oGroup.Users)\n                    {\n                        Response.Write(oUser.Name);\n\n                    Label l = new Label();\n                    l.Text = oUser.Name;\n\n                    PlaceHolderContents.Controls.Add(l);\n                    PlaceHolderContents.Controls.Add(new LiteralControl("<br/>"));\n                }\n            }	0
2747315	2747114	Linq-to-Entities Dynamic sorting	ItemType items = default(ItemType);\nswitch(sortColumn)\n{\n     case "Title":\n     {\n           items = ctxModel.Items\n                    .Where(i => i.ItemID == vId)\n                    .OrderBy( i => i.Title);\n     }\n     break;\n }	0
29998871	29998714	WPF Comparing values from diferent buttons	Textbox.Text	0
14531063	12772913	Open a PDF document and add bookmarks to it	private static List<HashMap<String, Object>> manipulatePdfBookMarkUtil(SortedMap<Integer, String> pgTtl, Rectangle rct) {\n    List<HashMap<String, Object>> mpBkMrkLst = null;\n    int itrCnt = 0;\n    if (pgTtl != null && !pgTtl.isEmpty()) {\n        mpBkMrkLst = new ArrayList<HashMap<String, Object>>();\n        for (Map.Entry<Integer, String> itrTtlPg : pgTtl.entrySet()) {\n            HashMap<String, Object> retMap = new HashMap<String, Object>();\n            retMap.put("Title", itrTtlPg.getValue());\n            retMap.put("Action", "GoTo");\n            retMap.put("Page", itrTtlPg.getKey() + " FitH " + rct.getTop());\n            mpBkMrkLst.add(itrCnt, retMap);\n            itrCnt++;\n        }\n    }\n    return mpBkMrkLst;\n    }	0
9747863	9747848	Split number in pieces of particular size	Num = num - (num % 10);\nlist<int> stuff;\nfor (int i = 0; i == (num /10); i++)\n     stuff.add((i*10));	0
24886959	24885985	How to put a self join with LINQ on XDocument?	var query =\n    doc\n        .Root\n        .Descendants("Event")\n        .Select(e =>\n            new XElement(\n                "Course",\n                e.Parent.Element("CourseId"),\n                e.Parent.Element("CourseName"),\n                e.Parent.Element("CourseDesc"),\n                e));	0
24369683	24368217	Split string after specific character or after max length	public static IEnumerable<string> SplitString(this string sInput, char search, int maxlength)\n    {\n        var result = new List<string>();\n        var count = 0;\n        var lastSplit = 0;\n\n        foreach (char c in sInput)\n        {\n            if (c == search || count - lastSplit == maxlength)\n            {\n                result.Add(sInput.Substring(lastSplit, count - lastSplit));\n                lastSplit = count;\n            }\n\n            count ++;\n        }\n\n        result.Add(sInput.Substring(lastSplit, count - lastSplit));\n\n        return result;\n    }	0
2952979	2952868	Fast and efficient way to read a space separated file of numbers into an array?	static void Main()\n    {\n        // sample data\n        File.WriteAllText("my.data", @"4 6\n1 2 3 4 5 6\n2 5 4 3 21111 101\n3 5 6234 1 2 3\n4 2 33434 4 5 6");\n\n        using (Stream s = new BufferedStream(File.OpenRead("my.data")))\n        {\n            int rows = ReadInt32(s), cols = ReadInt32(s);\n            int[,] arr = new int[rows, cols];\n            for(int y = 0 ; y < rows ; y++)\n                for (int x = 0; x < cols; x++)\n                {\n                    arr[y, x] = ReadInt32(s);\n                }\n        }\n    }\n\n    private static int ReadInt32(Stream s)\n    { // edited to improve handling of multiple spaces etc\n        int b;\n        // skip any preceeding\n        while ((b = s.ReadByte()) >= 0 && (b < '0' || b > '9')) {  }\n        if (b < 0) throw new EndOfStreamException();\n\n        int result = b - '0';\n        while ((b = s.ReadByte()) >= '0' && b <= '9')\n        {\n            result = result * 10 + (b - '0');\n        }\n        return result;\n    }	0
25561915	25561747	The C# String.Format() Format Controls	dgProducts.Columns["Unit Price"].DefaultCellStyle.Format = "c";\ndgProducts.Columns["Unit Price"].DefaultCellStyle.FormatProvider =  new CultureInfo("si-LK");	0
24850925	24843687	Programatically tell windows firewall to use the Private Network	INetFwRule firewallRule = (INetFwRule)Activator.CreateInstance(\n        Type.GetTypeFromProgID("HNetCfg.FWRule"));\n\n    INetFwPolicy2 firewallPolicy = (INetFwPolicy2)Activator.CreateInstance(\n        Type.GetTypeFromProgID("HNetCfg.FwPolicy2"));\n\n    firewallRule.ApplicationName = "<path to your app>";\n\n    firewallRule.Action = NET_FW_ACTION_.NET_FW_ACTION_ALLOW;\n    firewallRule.Description = " My Windows Firewall Rule";\n    firewallRule.Enabled = true;\n    firewallRule.InterfaceTypes = "All";\n    firewallRule.Name = "<your rule name>";\n\n    // Should really check that rule is not already present before add in\n    firewallPolicy.Rules.Add(firewallRule);	0
13083296	13082880	make border in Excel Cell using C#	sheet.Range["G3"].IsWrapText = true;	0
2332552	2332497	Refresh Page on a Specific Time in ASP.NET	DateTime targetDate = ...;\nlong secondsTilRefresh = Math.Floor((targetDate - DateTime.Now).TotalSeconds);	0
14374630	14374541	Should I call Parameters.Clear when reusing a SqlCommand with a transation?	try\n{\n    command.CommandText = "UPDATE Item SET payment_method_id = @batchID WHERE id in (@itemIDs)";\n    command.Parameters.Add(new SqlParameter("@batchID", 0));\n    command.Parameters.Add(new SqlParameter("@itemIDs", ""));\n\n    foreach (var itemIDs in this.SelectedItemIds)\n    {\n        command.Parameters["@batchID"].Value = batchID;\n        command.Parameters["@itemIDs"].Value = itemIDs;\n        command.ExecuteNonQuery();\n    }\n    transaction.Commit();\n}	0
22537390	22537190	Getting rid of a generic declaration	public interface IUserRepository : IRepository<User>\n{\n    void Authenticate(Useruser);\n}\n\n// and it's implementation:\n\npublic class UserRepository : BaseRepository<User>, IUserRepository\n{\n    public void Authenticate(User user)\n    {\n        // do some stuff here\n    }\n}	0
16380754	16380194	unable to add a node in avl_tree	while (true)\n        {\n            parent = current;\n            if (i < current.Data)\n                // you never get in here, so we just loop around in "while (true)"	0
593406	593388	How do i read a base64 image in WPF?	byte[] binaryData = Convert.FromBase64String(bgImage64);\n\nBitmapImage bi = new BitmapImage;\nbi.BeginInit();\nbi.StreamSource = new MemoryStream(binaryData);\nbi.EndInit();\n\nImage img = new Image();\nimg.Source = bi;	0
19516266	19515808	Check for decreasing values in a list	var lastBalance = decimal.MaxValue;\nforeach (DataRow dr in dt.Rows)\n{\n    if (!string.IsNullOrEmpty(dr[1].ToString()))\n    {\n        var currentBalance = Convert.ToDecimal(dr[1]);\n        if (currentBalance < lastBalance)\n        {\n            lastBalance = currentBalance;\n            balances.Add(dr[1].ToString());\n        }\n        else\n        {\n            //TODO: Invalid list\n            //throw ... OR\n            break;\n        }\n    }\n}	0
30743059	30742494	Writing information from SQL Server to C#	try\n{\n    using(SqlConnection connect = new SqlConnection(....))\n    using(SqlCommand command = new SqlCommand(\n        @"SELECT FILE_DATE_PROCESSED, DATE_ENTERED FROM FILE_DATE_PROCESSED", connect))\n    {\n        connect.Open();\n        using(SqlDataReader reader = command.ExecuteReader())\n        {\n           while (reader.Read())\n           {\n                 Console.WriteLine(reader["FILE_DATE_PROCESSED"].ToString());\n                 Console.WriteLine(reader["DATE_ENTERED"].ToString());\n           }\n        }\n   }\n}\ncatch (Exception e)\n{\n   Console.WriteLine(e.ToString());\n}	0
11396752	11396679	How do I call a static property of a generic class with reflection?	public class Foo<T>\n{\n    public static string MyMethod()\n    {\n        return "Method: " + typeof(T).ToString();\n    }\n}\n\nclass Program\n{\n    static void Main()\n    {\n        Type myType = typeof(string);\n        var fooType = typeof(Foo<>).MakeGenericType(myType);\n        var myMethod = fooType.GetMethod("MyMethod", BindingFlags.Static | BindingFlags.Public);\n        var result = (string)myMethod.Invoke(null, null);\n        Console.WriteLine(result);\n    }\n}	0
13119390	13119263	Copying sorted values from one datatable to another Efficiency?	EmpInfoDS = new DataSet();\ncon.Open(); // My connection name\nstring sqlRecords = "Select * FROM tbl_EmpInfo ORDER BY EmpID";\nEmpInfoDA = new OleDbDataAdapter(sqlRecords, con);\nEmpInfoDA.Fill(EmpInfoDS, "EmpInfo");\ncon.Close();	0
4276574	4276049	C# - Best (fastest) way to import data from text file to mdf	BULK\nINSERT MyTable\nFROM 'c:\myfile.txt'\nWITH\n(\nFIELDTERMINATOR = ',',\nROWTERMINATOR = '\n'\n)	0
504628	504598	Adding a horizontal separator in a MenuStrip	this.menuMain.Items.Add(new ToolStripSeparator());	0
15363601	15363478	Read all files in directory sub folders	var dir = new DirectoryInfo(@"c:\scripts");\nforeach(var file in dir.EnumerateFiles("*.html",SearchOption.AllDirectories))\n{\n\n}	0
15388285	15387749	Combining boolean Observables	c3 = c1.CombineLatest(c2, (a, b) => a && b).DistinctUntilChanged()	0
3874688	3874616	Deleting a directory	private static void FileCleanup(string directoryName)\n{\n    try\n    {\n        string[] filenames = Directory.GetFiles(directoryName);\n\n        foreach (string filename in filenames)\n        {\n            File.Delete(filename);\n        }\n\n        if (Directory.Exists(directoryName))\n        {\n            Directory.Delete(directoryName);\n        }\n    }\n    catch (Exception ex)\n    {\n       // you might want to log it, or swallow any exceptions here\n    }\n}	0
10308360	10306910	Controlling ListBox scrolling behaviour	ListBox listBox1 = new ListBox();\n\nlistBox1.SetValue(ScrollViewer.HorizontalScrollBarVisibilityProperty,\nScrollBarVisibility.Disabled);\n\nlistBox1.SetValue(ScrollViewer.VerticalScrollBarVisibilityProperty, \nScrollBarVisibility.Disabled);\n\nlistBox1.SetValue(ScrollViewer.CanContentScrollProperty, false);\n\nlistBox1.SetValue(ScrollViewer.IsDeferredScrollingEnabledProperty, true);	0
21596014	21594501	Combining latest from an observable of observables	var downStream = statusStream\n    .Aggregate<WebsiteStatus, IEnumerable<string>>(new string[0], (down, newStatus) =>\n    {\n        if (newStatus.IsUp)\n            return down.Where(uri => uri != newStatus.Uri);\n        else if (!down.Contains(newStatus.Uri))\n            return down.Concat(new string[] { newStatus.Uri });\n        else\n            return down;\n    });\n\nvar upStream = statusStream\n    .Aggregate<WebsiteStatus, IEnumerable<string>>(new string[0], (up, newStatus) =>\n    {\n        if (!newStatus.IsUp)\n            return up.Where(uri => uri != newStatus.Uri);\n        else if (!up.Contains(newStatus.Uri))\n            return down.Concat(new string[] { newStatus.Uri });\n        else\n            return up;\n    });\n\nvar allDown = upStream.Select(up => !up.Any());	0
6702780	6702729	DataGridView ComboBox EditingControlShowing events	int row = dgvHardware.CurrentCell.RowIndex;	0
20217673	20217261	Taking average value every 2 seconds	/* add current samples to totals */\n total_u += u_dcbus_pv_act[i];\n total_p += p_dcbus_pv_act[i];\n\n /* every fourth tick, calc average and reset totals */\n if (i % 4 == 0)\n {\n     average_u = total_u / 4;\n     average_p = total_p / 4;\n     total_u = 0;\n     total_p = 0;\n }\n u_dcbus_target = average_u;\n p_dcbus_pv_avg = average_p;\n i++;	0
19661828	19660401	C# Monotouch/Xamarin - Replace Entire Tab Button With Image In UITabBarController	var tabBarItem = new UITabBarItem("Item Text", null, 1);\ntabBarItem.SetFinishedImages(UIImage.FromBundle("./Images/addexpense.png"), UIImage.FromBundle("./Images/addexpense.png"));\n\nvar controllerToAdd = new UIViewController()\n{\n    TabBarItem = tabBarItem\n};\n\ntabBarController.SetViewControllers(new UIViewController[]\n{\n controllerToAdd\n};	0
8996242	8996184	Do you know how to parse a string to nullable<int>?	public int? NullableInt(string str)\n    {\n        int i;\n        if (int.TryParse(str, out i))\n            return i;\n        return null;\n    }	0
944797	944766	C#: Wait for variable to become non-null	private ManualResetEvent mre = new ManualResetEvent(false);\n\nprivate void OpenForm()\n{\n    if (FormThread == null)\n    {\n        FormThread = new Thread(FormStub);\n        FormThread.SetApartmentState(ApartmentState.STA);\n        FormThread.Start();\n        mre.WaitOne();\n    }\n}\n\nprivate void FormStub()\n{\n    Form = new ConnectorForm();\n    mre.Set();\n    Application.Run(Form);\n}	0
11404749	11404690	finding listview column index using simple key string	string selectedItemMouthColumn = listView.SelectedItems[0].SubItems[listView.Columns.IndexOf(MOUTH)].Text;	0
32168074	32167804	Set Authorization Header of HttpClient	client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("key", "=" + apiKey);	0
1849112	1849044	How to perform 2 checks in LINQ Where	List<SavedOption> finalSavedOptions = savedOptions.Where(x => \n    itemOptions.Any(y => OptionTextDoesMatch(y, x) && y.SomeID == x.SomeID)\n).ToList();	0
12865710	12865634	Controlling multiple windows	public NewOne()\n{\n  InitializeComponent();\n\n  LoginWindow login = new LoginWindow();\n  bool? result = login.ShowDialog();\n  if (!result.HasValue || result.Value == false)\n    this.Close();\n}	0
19963397	19963074	how to get sum dynamically of datagridview column in textbox	private void dataGridView2_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n    {\n        if (e.ColumnIndex == 5)\n            textBox9.Text = CellSum().ToString();\n    }\n\n    private double CellSum()\n    {\n        double sum = 0;\n        for (int i = 0; i < dataGridView2.Rows.Count; ++i)\n        {\n            double d = 0;\n            Double.TryParse(dataGridView2.Rows[i].Cells[5].Value.ToString(), out d);\n            sum += d;\n        }\n        return sum;\n    }	0
30808793	30808710	How to get two zeros after decimal value	txt_netamount.Text = decimalValue.ToString("0.00");	0
5597041	5596506	Windows Phone 7: How to parse Bezier Path string like in XAML?	Path path = XamlReader.Load("<Path xmlns='http://schemas.microsoft.com/winfx/2006/xaml/presentation' Stroke='Blue' Data='M 0 0 Q 10 10 20 0'/>") as Path;	0
24161814	24161693	How to corectly Loop over days	for (DateTime date = StartDate.AddDays(nrOfDaysToLoopBy-1); date.Date <= EndDate.Date; date = date.AddDays(nrOfDaysToLoopBy))\n {\n  }	0
24358540	24358520	How to find the items that are repeated only once in the list using LINQ	var query = Points\n    .GroupBy(p => new { p.X, p.Y }) // Group points based on (X,Y).\n    .Where(g => g.Count() == 1)     // Take groups with exactly one point.\n    .Select(g => g.Single());       // Select the point in each group.	0
8568465	8567709	RegEx expressions with replacement and extracting values	private static void Main()\n{\n    Regex pattern = new Regex(@"(?<Name>[\w\-_]+)\.+(?<Value>[\w\-_]+)");\n    string sample = @"(123456789..value > 2000) && (987654321.Value < 12)";\n\n    string result = pattern.Replace(sample,\n                                    m =>\n                                    String.Format(\n                                        "ClassName.GetInfo(\"{0}\").Get{1}{2}()",\n                                        m.Groups["Name"].Value,\n                                        Char.ToUpper(m.Groups["Value"].Value[0]),\n                                        m.Groups["Value"].Value.Substring(1))\n        );\n    Console.WriteLine(result);\n}	0
7806515	7806380	from derived class to base class	public class Team\n{\n  private IList<Player> _players\n  ...\n}\n\npublic class Player\n{\n  public string Name {get;set;}\n\n  public abstract Influence { get; }\n}\n\npublic class Forward : Player\n{\n  public override Influence\n  {\n    get { return //calculation }\n  }\n}	0
17199533	17199276	Positioning a control Code behind	panelNew.Style[HtmlTextWriterStyle.Position] = 'absolute';\npanelNew.Style[HtmlTextWriterStyle.ZIndex] = '999';	0
33792305	33792232	How can I edit particular word one by one in a text line?	string s = "His name is Jack. Jack likes to ride a bike";\nint count = 0;\nstring s2 = Regex.Replace(s, "Jack", match => {\n    count++;\n    return count > 1 ? "Jack2" : "Jack1";\n});	0
12389606	12389588	Validating Array to Array Exist in Lamda or Linq	using System.Linq;\n\nif (!array2.Except(array1).Any())\n{\n    ...validated!\n}	0
19937482	19937336	BitmapImage CreateOptions in code	BitmapImage bimg = new BitmapImage();                        \nbimg.CreateOptions = BitmapCreateOptions.BackgroundCreation \n                     | BitmapCreateOptions.IgnoreImageCache	0
7368516	7368477	How to crop a part of a image	Graphics.DrawImage	0
11915912	11884976	Query Data Using LINQ C# With Filter string[] array?	// now filter proptypes to selected Types|\nvar myTAccomtypes = from d in connection.Get<ALocal.proptype>().ToList()\n    // ToList() will evaluate collection, you cannot pass sTypes array of integers to a sql query, at least not in that way\n    where sTypes.Contains(d.proptype_id.ToString())\n    select new { d.proptype_id, d.proptype_name };\n\n    DataTable AcomType = LINQToDataTable(myTAccomtypes);\n\n    StringBuilder sb = new StringBuilder();\n    // Loop over table rows\n    foreach (var row in AcomType.Rows.OfType<DataRow>().Take(19))  // will .Take up to a maximum of x rows from above\n    {\n         sb.Append("<dd>");\n         sb.Append(row["proptype_name"].ToString());\n         sb.Append("</dd>");\n     }\n     HldUserSet.TuAccomtypes = sb.ToString();\n     //HldUserSet.TuAccomtypes = string.Join(",", myTAccomtypes); //Check query content	0
3279049	3279017	How to sort a List in C#	class Program\n{\n    static void Main(string[] args)\n    {\n        var list = new List<MyObject>(new[]\n        {\n            new MyObject { Name = "ABC", Age = 12 },\n            new MyObject { Name = "BBC", Age = 14 },\n            new MyObject { Name = "ABC", Age = 11 },\n        });\n        var sortedList = from element in list\n                         orderby element.Name\n                         orderby element.Age\n                         select element;\n\n        foreach (var item in sortedList)\n        {\n            Console.WriteLine("{0} {1}", item.Name, item.Age);\n        }\n    }\n}	0
1576143	1575445	Checkbox in TemplateField in Gridview loses checked on postback	if (!Page.IsPostBack)\n    {\n        GridView1.DataSourceID = "yourDatasourceID";\n        GridView1.DataBind();\n    }	0
13654701	13340503	Add handler to any event with reflection, handle dynamically	object HandleEvent(object[] parameters)	0
2766967	2766928	How to set username and password for SmtpClient object in .NET?	SmtpClient mailer = new SmtpClient();\nmailer.Host = "mail.youroutgoingsmtpserver.com";\nmailer.Credentials = new System.Net.NetworkCredential("yourusername", "yourpassword");	0
13299236	13298805	C#: How to select the top item in a listview after sorting	private void Populate(object sender, EventArgs e)\n    {   \n        listView1.Items.Add("D");\n        listView1.Items.Add("B");\n        listView1.Items.Add("A");\n        listView1.Items.Add("C");\n    }\n\n    private void SelectFirst(object sender, EventArgs e)\n    {\n        listView1.Items[0].Selected = true;\n        listView1.Select();\n    }\n\n    private void SortAndSelect(object sender, EventArgs e)\n    {\n        listView1.Sorting = SortOrder.Ascending;\n        listView1.Sort();\n\n        listView1.Items[0].Selected = true;\n        listView1.Select();\n    }	0
26290836	26290800	Swap two integers without using a third variable for all range of integer values	if (a != b) {\n    a ^= b;\n    b ^= a;\n    a ^= b;\n}	0
23418165	23418099	Checking if a date picker value is less than todays date MVC	public ActionResult Create(Job job)\n{\n    if (job.TargetDateSurvey.Value < DateTime.Today)\n    {\n        ModelState.AddModelError("TargetDateSurvey", "Date must be today or later.");\n    }\n\n    if (ModelState.IsValid)\n    ...\n}	0
20784315	20784177	how can we update data in database using entityframework in windows form application.?	GameSchedulingEntities db = new GameSchedulingEntities();\n        Group obj = db.Groups.Find(Id);\n        // or Group obj = db.Groups.FirstOrDefault(g => g.Name == NametextBox.Text);\n        obj.Name = somethingelse;\n        db.SaveChanges();	0
31215992	31215859	Linq multiple select by xml attributes	XNamespace ns = "http://www.ecb.int/vocabulary/2002-08-01/eurofxref";\nvar xdoc = XDocument.Load(@"http://www.ecb.europa.eu/stats/eurofxref/eurofxref-hist-90d.xml");\nvar names = new[] { "USD", "RON", "SMT" };\nvar someCubes =  xdoc.Root.Element(ns + "Cube")\n    .Elements()\n    .Select(x => x.Elements()\n    .Where(y => names.Contains(y.Attribute("currency").Value)))\n    .Select(x => {\n        return x.Select(y => {\n            return new {\n                datum = (DateTime)y.Parent.Attribute("time"),\n                currency = (string)y.Attribute("currency"),\n                rate = (string)y.Attribute("rate")\n            };\n        });\n    });	0
24532547	24531035	C# Create array from MatchCollection	string input = "[PC(name=\"PC1\", ip=\"192.168.1.2\", subnet=\"255.255.255.0\", gateway=\"192.168.1.1\")]\n[PC(name=\"PC2\", ip=\"192.168.1.3\", subnet=\"255.255.255.0\", gateway=\"192.168.1.1\")]";\n\n       MatchCollection matches = Regex.Matches(input, @"name=""(.*?)"".*ip=""(.*?)"".*subnet=""(.*?)"".*gateway=""(.*?)""");\n\n       object[][] values = matches.OfType<Match>()\n                           .Select(m => new object[] { m.Groups[1], m.Groups[2], m.Groups[3], m.Groups[4] })\n                           .ToArray();	0
23428704	23428602	Retrieving value from html select	protected void Page_Load(object sender, EventArgs e)\n    {\n      if (!IsPostBack)\n        {\n         InstanceData = (DataSet)(Session["InstanceData"]);\n         id1.DataSource = InstanceData.tables[0];\n         id1.DataTextField = "DB";\n         id1.DataValueField = "DB";\n         id1.DataBind();\n        }\n    }\n\n protected void Button1_Click(object sender, EventArgs e)\n    {\n        string DataBase = id1.SelectedValue;\n    }	0
5902087	5902018	Checking a folder for a file	var regex = new Regex(@"^E\d\d$");\nvar file = Directory.GetFiles(path, "E??.chk")\n                    .Where(f => regex.IsMatch(File.GetFileNameWithoutExtension(f)))\n                    .OrderBy(f => f)\n                    .FirstOrDefault();	0
17711569	17711481	Determine MessageBoxIcon Based on ComboBox	MessageBox.Show("Text", "Text", MessageBoxButtons.OK,\n(MessageBoxIcon)Enum.Parse(typeof(MessageBoxIcon), ComboBox.Text.ToString());	0
9986119	9985902	How to configure Windows Group Policy using c++?	Group Policy Settings Reference for Windows and Windows Server	0
18767942	18766738	Is it possible to receive a soap message in a WCF method?	[OperationContract(Action="*", ReplyAction="*")]\n    System.ServiceModel.Channels.Message ProcessMessage(System.ServiceModel.Channels.Message msg);\n}	0
912104	912062	How to save picture in the database?	myObject.Image = new Binary(imageByteArray);	0
24862148	24862088	Using LINQ on XML data source	XNamespace ns = "http://www.example.com/Modules";\n\nvar courses = from e in doc.Descendants(ns + "Module")\n            let lowname = e.Value.ToLowerInvariant()\n            where lowname.Contains("linq")\n            orderby e.Value\n            select e.Value;	0
980515	980489	Resizable table layout panel in c#	????????????????????\n????????????????????\n??     ?          ??\n??     ?          ??\n????????????????????\n????????????????????\n????????????????????\n??          ?     ??\n??          ?     ??\n????????????????????\n????????????????????	0
11156383	11155845	How to read 1MB .tif file with bitmap class in c#	using System;\nusing System.IO;\nusing System.Linq;\nusing System.Windows.Media.Imaging;\n\nclass Program\n{\n    static void Main()\n    {\n        using (var stream = File.OpenRead(@"c:\work\some_huge_image.tif"))\n        {\n            var decoder = BitmapDecoder.Create(stream, BitmapCreateOptions.None, BitmapCacheOption.None);\n            var frame = decoder.Frames.First();\n            Console.WriteLine(\n                "width: {0}, height: {1}", \n                frame.PixelWidth, \n                frame.PixelHeight\n            );\n        }\n    }\n}	0
28194169	28193741	How to get to the properties of a generic class in a list?	public class StationProperty<T> : StationProperty\n{\n    public StationProperty()\n    {\n    }\n\n    public StationProperty(int id, T val, string desc = "")\n    {\n        Id = id;\n        Desc = desc;\n        Value = val;\n    }\n\n    public int Id { get; set; }\n    public string Desc { get; set; }\n    public T Value { get; set; }\n\n    object StationProperty.Value\n    {\n        get { return Value; }\n    }\n\n    public Type ValueType\n    {\n        get { return typeof (T); }\n    }\n}\n\npublic interface StationProperty\n{\n    int Id { get; set; }\n    string Desc { get; set; }\n    object Value { get; }\n    Type ValueType { get; }\n}	0
8248788	8248603	C# limit length of a string	public class VendorClass\n{\n    public int VendorID {  get; set; }\n\n    private string _vendorName;\n\n    public string VendorName\n    {\n        get { return _vendorName; }\n        set\n        {\n            if (value.Length > 15)\n            {\n                _vendorName = value.Substring(0,15);                    \n            } else { \n                _vendorName = value;\n            }\n        }\n    }\n}	0
8577349	8577307	strip out only left most letters from a string, only the left side letters	var onlyLetters = new String(fileName.Name.TakeWhile(Char.IsLetter).ToArray());	0
29449584	29402274	RTB SelectAll only working on last item in StackPanel	Keyboard.ClearFocus();	0
20209690	20209630	How to compare const hex and int?	class Program\n{\n\n    private const int CONST_INT = 0x10;\n    static void Main(string[] args)\n    {\n        Console.WriteLine(CONST_INT==16);\n    }\n}	0
2820892	2820312	Add Table to FlowDocument In Code Behind	...\nvar rg = new TableRowGroup();\nrg.Rows.Add(row);\nt.RowGroups.Add(rg);\n_doc2.Blocks.Add(t);	0
829328	829276	Build configuration in C# code	#if DEBUG\n        RunMyDEBUGRoutine();\n#else\n        RunMyRELEASERoutine();\n#endif	0
2431931	2431739	Assign multiple lines in single cell in Excel using C#	Excel.Range dataRange= (Excel.Range)excelWorksheet.get_Range("C4", "C4");\ndataRange.Value2 = "This is the first line\n" +\n        "This is the second line\n" +          \n        thirdLineString;	0
29411098	29369275	How to select date in selenium Webdriver from ajax calendarextender using C#	IList<IWebElement> row = date.FindElements(By.TagName("tr"));\n        IList<IWebElement> col = date.FindElements(By.TagName("td"));\n\n        foreach (IWebElement cell in col)\n        {\n            if (cell.Text.Equals("13"))  \n            {\n                cell.Click();\n                break;\n            }    \n        }	0
295703	295538	How to provide user name and password when connecting to a network share	using (new NetworkConnection(@"\\server\read", readCredentials))\nusing (new NetworkConnection(@"\\server2\write", writeCredentials)) {\n   File.Copy(@"\\server\read\file", @"\\server2\write\file");\n}	0
12207262	12206963	UrlAcl Info in Registry	netsh http show urlacl	0
12002914	12002802	Linq-to-SQL database file empty	using(DataShemeDataContext context = new DataShemeDataContext("Data Source=database.sdf"))\n{\n    if (!context.DatabaseExists())\n        context.CreateDatabase();\n}\nConsole.ReadLine();	0
31105535	31098717	How force close all IE processes - with alert() on form_unload	private void Kill_IE()\n{\n    Process[] ps = Process.GetProcessesByName("IEXPLORE");\n\n    foreach (Process p in ps)\n    {\n        try\n        {\n            if (!p.HasExited)\n            {\n                p.Kill();\n            }\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(String.Format("Unable to kill process {0}, exception: {1}", p.ToString(), ex.ToString()));\n        }\n    }\n}	0
28423173	28423078	TryParseExact failing with DateTime	string format = "MM/dd/yyyy h:mm:ss tt";	0
26999763	26999471	Calling a web method from Windows Phone 8	using (var client = new HttpClient())\n{\n    var resp = await client.PostAsJsonAsync("http://your host/Login.aspx/Login", \n                                             new { username = "", password = "" });\n\n    var str = await resp.Content.ReadAsStringAsync();\n}	0
8066411	8066333	Combo Box Enter Event WPF	private void comboBox1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Key == Key.Return)\n        {         \n           // do stuff\n        }\n        else\n        {\n\n            // do stuff       \n        }\n    }	0
13347407	13347338	Retrieve a number from a table by EF	InContext inContext = new InContext(cnStr);\n// get first biggest item\nBatchPINDetail entity = inContext.BatchDetailsRecords\n                                 .OrderByDescending(x => x.Number)\n                                 .First();\n// get all biggest items\nBatchPINDetail entities = inContext.BatchDetailsRecords\n                                 .Where(x => x.Number == x.Max(x => x.Number))\n                                 .ToArray();\n\n// and if you just want to get biggest number. \n// but note that if you just change `num` nothing will happen.\nint num = inContext.BatchDetailsRecords.Max(x => x.Number);\n\nentity.Number += 1;\ninContext.SaveChanges();	0
11108470	11105480	how to printout my C# string values into formatted text to print it using printer, BioPDF printer, Bullzip software	PrintDialog printDialog = new PrintDialog();\nif (printDialog.ShowDialog().GetValueOrDefault(false))\n{\n    printDialog.PrintVisual(this, this.Title); \n}	0
13730686	10667561	C# - SSH Winforms Emulate console	//Writing to the SSH channel\nssh.Write( command );\n\n//Reading from the SSH channel\nstring response = ssh.ReadResponse();	0
23052385	23026319	Displaying all images from directory	string imagepath = Server.MapPath("~/Images/");\n        string[] images =Directory.GetFiles(imagepath,"*.png",SearchOption.TopDirectoryOnly);\n\n        foreach (string filepath in images)\n        {\n\n\n            Image te = new Image();\n\n            string fileurl = Path.GetFileName(filepath.ToString());\n\n            te.ImageUrl = "~/Images/" + fileurl;\n            te.Height = 100;\n            te.Width = 200;\n            te.CssClass = "zoom";\n            //Here myimages is my div in which all images will be added.\n            myimages.Controls.Add(te);\n\n\n\n        }	0
16649803	16643576	Get the list of all users in a particular user group using Ektron API	List<UserData> userData = new List<UserData>();\nEktron.Cms.API.User.User user = new Ektron.Cms.API.User.User();\nlong groupId = Id; //your group id\nforeach (UserData u in user.GetUsers(groupId, "username")) //group id + sort by field\n{\n    userData.Add(user.GetUser(u.Id));\n}\nreturn userData;	0
17914576	17914448	How can I find the type of a datasource?	List<ContactEvent>	0
18056829	18056520	Removing the same method from Event	private static void A(Object sender, EventArgs e) {\n  Console.Out.Write('A');\n}\n\nprivate static void B(Object sender, EventArgs e) {\n  Console.Out.Write('B');\n}\n\n...\n\nEventHandler eh = null;\n\neh += A;\neh += A;\neh += B;\neh += A;\neh -= A;\n\neh(null, EventArgs.Empty);	0
17838361	17830110	Entity Framework HasOptional In Data Annotations	[ForeignKey("VirtualTerminalId")]\npublic VirtualTerminal VirtualTerminal { get; set; }	0
23438067	23438008	How to find out if a download has finished?	using (var file = File.OpenWrite(localFileName))	0
4675939	4675874	Do I need a BindingSource AND a BindingList for WinForms DataBinding?	BindingList<T>	0
11729682	11728721	How to globally handle "The parameters dictionary contains a null entry for parameter x"	public ActionResult Index(int id = 0, string name = "user") { ... }	0
11092851	11092746	How to eliminate spurious/superfluous spaces within a foreach loop?	List<string> logLineElements = line.Split('|').Select(e => e.Trim()).ToList();	0
20526081	20525615	Reading from closed NetworkStream doesn't cause any exception	//\n// Time-out after 1 minute after receiving last message\n//\nstream.ReadTimeOut = 60 * 1000;\n\nBinaryFormatter deserializer = new BinaryFormatter();\n\ntry\n{\n    while (!interrupted)\n    {\n        System.Diagnostics.Debug.WriteLine("Waiting for the message...");\n        AbstractMessage msg = (AbstractMessage)deserializer.Deserialize(stream);\n        System.Diagnostics.Debug.WriteLine("Message arrived: " + msg.GetType());\n\n        //\n        // Exit while-loop when receiving a "Connection ends"  message.\n        // Adapt this if condition to whatever is appropriate for\n        // your AbstractMessage type.\n        //\n        if (msg == ConnectionEndsMessage) break;\n\n        raiseEvent(msg);\n    }\n}\ncatch (IOException ex)\n{\n    ... handle timeout and other IOExceptions here...\n}	0
24320649	24320487	How to run the MediaPlayer on repeat mode in C# WPF?	private void Media_Ended(object sender, EventArgs e)\n{\n    media.Position = TimeSpan.Zero;\n    media.Play();\n}	0
4556504	4556411	How to hide a window in start in c# desktop application?	using System;\nusing System.Windows.Forms;\n\nnamespace DelayedShow\n{\n  public partial class Form1 : Form\n  {\n    private bool _canShow = false;\n    private Timer _timer;\n\n    public Form1()\n    {\n      InitializeComponent();\n      _timer = new Timer();\n      _timer.Interval = 5000;\n      _timer.Tick += new EventHandler(timer_Tick);\n      _timer.Enabled = true;\n    }\n\n    void timer_Tick(object sender, EventArgs e)\n    {\n      _canShow = true;\n      Visible = true;\n    }\n\n    protected override void SetVisibleCore(bool value)\n    {\n      if (_canShow)\n      {\n        base.SetVisibleCore(value);\n      }\n      else\n      {\n        base.SetVisibleCore(false);\n      }\n    }\n  }\n}	0
15890560	15876235	How to add custom TFS CheckinNoteDefinitions?	var checkinNoteFieldValues = new[]\n{\n    new CheckinNoteFieldValue("Custom Note", "some value"),\n    new CheckinNoteFieldValue("Other Note", "other value")\n};\nvar checkinNote = new CheckinNote(checkinNoteFieldValues);\nvar pendingChanges = workspace.GetPendingChanges(); // workspace is Microsoft.TeamFoundation.VersionControl.Client.Workspace\nworkspace.CheckIn(pendingChanges, "comment", checkinNote, null, null); // checkinNote will trigger a new CheckinNoteFieldDefinition	0
7553753	7553685	Creating DateTime object from DatePicker and TimePicker control	DateTime MyDateTime = ((DateTime) MyDatePicker.Value).Date.Add (((DateTime)MyTimePicker.Value).TimeOfDay);	0
3794638	3791086	ControlTemplate.Resources in a code-behind file	Template.Find("name of resource")	0
10165854	10163715	Get user information on the Facebook profile page	{\n   "error": {\n      "message": "An access token is required to request this resource.",\n      "type": "OAuthException",\n      "code": 104\n   }\n}	0
19147276	19147184	How to find the distance between two pixels in c#?	double dist = Math.Sqrt(Math.Pow(x2 - x1, 2) + Math.Pow(y2 - y1, 2));	0
8470872	8470690	how to take dictionary's top N values in c# by linq?	var firstN = dict.ToDictionary(\n                  kvp => kvp.Key,\n                  kvp => kvp.Value.Take(CONST_MAX).ToList());	0
8696458	8696405	Foreach over multiple ControlCollections	foreach (var ctrl in panels.SelectMany (x => x.Cast<Control> ())) {\n     // Work with the control.\n}	0
4529688	4529608	Combine two regex group into a key/value pair object?	System.Collections.Generic.Dictionary<string, string> hashTable = new System.Collections.Generic.Dictionary<string, string>();\n\nstring myString = "Type=\"Category\" Position=\"Top\" Child=\"3\"";\nstring pattern = @"([A-Za-z0-9]+)(\s*)(=)(\s*)("")([^""]*)("")";\n\nSystem.Text.RegularExpressions.MatchCollection matches = System.Text.RegularExpressions.Regex.Matches(myString, pattern);\nforeach (System.Text.RegularExpressions.Match m in matches)\n{\n    string key = m.Groups[1].Value;    // ([A-Za-z0-9]+)\n    string value = m.Groups[6].Value;    // ([^""]*)\n\n    hashTable[key] = value;\n}	0
3913280	3913241	How to insert null into database?	if(string.IsNullOrEmpty(sbcId))\n    Parameters.Add(new OleDbParameter("EMPID", DBNull.Value)); \nelse\n    Parameters.Add(new OleDbParameter("EMPID", sbcId));	0
11613786	11613380	Comparing two custom objects	IEnumerable<KeyValuePair<Filter, string>> DoIt(Dictionary<Filter, string> dict, Filter f)\n    {\n        return dict.Where\n            (d => \n                (f.A == null || d.Key.A == f.A) && \n                (f.B == null || d.Key.B == f.B) && \n                (f.Start == null || f.Start < d.Key.Start) /* && Condition for End */);\n    }	0
32429947	32428719	C# Datagridview Image Column only displaying one image	foreach (DataGridViewRow dgRow in dgvPatList.Rows)\n{\n    if (dgRow.Cells[0].Value == null) continue;  //Change if you wish no_results to be shown\n\n    dgRow.Cells["NPOIMG"].Value = dgRow.Cells[0].Value.ToString() == "1" \n         ? Properties.Resources.Tick_Green \n         : Properties.Resources.no_results;\n}	0
17559197	17558840	Changing one column in a dataset	foreach (object item in row.ItemArray)\n{\n     DateTime parsed;\n     if (DateTime.TryParse(item.ToString(), out parsed))\n     {\n          writer.Write(String.Format("{0,-10}", parsed.ToString("MM-dd-yy") + ""));\n     }\n     else \n     {\n          writer.Write(String.Format("{0,-10}", item.ToString() + ""));\n     }\n}\n\n\n\nforeach (DataColumn col in jackTDataSet.Tables[0].Columns)\n{\n     if (col.ColumnName == "Name of date Field ")\n     {\n         writer.Write(String.Format("{0,-10}", ((DateTime)row[col.ColumnName]).ToString("MM-dd-yy") + ""));\n     }\n     else \n     {\n         writer.Write(String.Format("{0,-10}", row[col.ColumnName].ToString() + ""));\n     }\n}	0
10480708	10480679	How to set list items to null C#?	while (panel.Controls.Count > 0)\n  {\n     panel.Controls[0].Dispose();\n  }	0
23700829	23700731	instantiating a class into a variable or not	Option1:\nIL_0000:  newobj      UserQuery+SomeObjectModel..ctor\nIL_0005:  stloc.0     // TheObjectModel\nIL_0006:  ldloc.0     // TheObjectModel\nIL_0007:  callvirt    UserQuery+SomeObjectModel.SomeMethod\nIL_000C:  ret         \n\nOption2:\nIL_0000:  newobj      UserQuery+SomeObjectModel..ctor\nIL_0005:  call        UserQuery+SomeObjectModel.SomeMethod\nIL_000A:  ret	0
26085693	26085674	Is there a way I can create a class or anonymous object to be used in a Generic <> inside a method?	Query<T> SqlQuery<T>(string query, T sample) {\n    // Ignore the sample parameter\n}\n\nSqlQuery("...", new { Abc = 0, Def = 0 })	0
6024896	6024875	How to access application resources in code, c#, wp7	btn.Style = Application.Current.Resources["ButtonStyle"] as Style;	0
20727547	20727525	Calculate inches and centimeters from pixels in C#	points = pixels * 72 / 96	0
9412693	9412672	Lambda expressions with multithreading in C#	public void processinThreads()\n{\n    for (int i = 0; i < 20; i++)\n    {\n        int local = i;\n        Thread t = new Thread(new ThreadStart(()=>DoSomething(local, processCallback)));\n        t.Start();\n    }\n}	0
1681052	1681037	How to convert IEnumerable<char> to string[] so I can use it with String.Join?	string[] foo = nonLetters.Select(c => c.ToString()).ToArray();	0
15125592	15123700	SqlTransaction to support multiple SqlConnections	using(System.Transacation.TransactionScope myScope = new TransactionScope()){\n  //all of your sql connections and work in here\n\n  //call this to commit, else everything will rollback\n  myScope.Complete();\n}	0
2957103	2957042	Get the file path of current application's config file	string folder = System.Web.HttpContext.Current != null ?\n    System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "App_data") :\n    System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);	0
2899089	2899050	Chain LINQ IQueryable, and end with Stored Procedure	Fishes_FulltextSearch("abc")	0
9834451	9834391	C# Minimum Number of Significant Figures	string format = "#.";\nwhile (list.GroupBy(x => x.ToString(format))\n           .Any(g => g.Count() > 1)\n      ) {\n    format += "#";\n}	0
4205026	4204840	Windows Form RTF formatting for the RichTextBox Control	{\rtf1\ansi\ansicpg1252\deff0\deflang6153{\fonttbl{\f0\fnil\fcharset0 Calibri;}}\n{\colortbl ;\red255\green0\blue0;}\n{\*\generator Msftedit 5.41.21.2509;}\viewkind4\uc1\pard\sa200\sl276\slmult1\lang9\b\f0\fs22 Datetime\b0  - \cf1 Event Type\cf0  - Event Details\par\n}	0
14362683	14340501	Loading third party assembly referenced only by plugins with AssemblyCatalog	arg.Name	0
8217052	8216881	How do I check if a List contains an object of a certain type? C#	public bool DetectBall(List<GameObject> Within)\n{\n    foreach(GameObject go in Within)\n    {\n        if(go is Ball) return true;\n    }\n\n    return false;\n}	0
7652836	7652738	How to limit KeyDown actions frequency	private DateTime _LastExecution = DateTime.MinValue;\n\npublic void UserControl_KeyDown(object sender, EventArgs ea) {\n    if ( ( DateTime.Now - _LastExecution ).TotalMilliSeconds > 500 ) {\n        /* do you stuff */\n        _LastExecution = DateTime.Now;\n    }\n}	0
8884724	8875774	Create instance from attribute	var container = new CompositionContainer(/* your container .ctor here */);\nvar type = typeof (IYourType); // read the type from attribute\nvar export = container.GetExports(type, null, null).FirstOrDefault();\nvar obj = export.Value as YourCostingHere;	0
16902277	16820855	Convert String To Int in LINQ	public bool GetElectricalStatus(string printName)\n    {\n        List<object> eGoodList = new List<object>();\n        var eGoodCountQuery =\n            from row in singulationOne.Table.AsEnumerable()\n            where row.Field<String>("print") == printName\n            select row.Field<String>("electrical");\n\n        foreach (var eCode in eGoodCountQuery)\n        {\n            if (!string.IsNullOrEmpty(eCode.ToString()))\n            {\n                int? eCodeInt = Convert.ToInt32(eCode);\n                if (eCodeInt != null &&\n                    (eCodeInt >= 100 && eCodeInt <= 135) || eCodeInt == 19)\n                {\n                    eGoodList.Add(eCode);\n                }\n            }\n        }\n        if (eGoodList.Count() > 0)\n        {\n            return false;\n        }\n        else\n        {\n            return true;\n        }\n    }	0
988422	988334	Using a DLL in Visual Studio C++	using namespace SomeNamespace;	0
12130915	12130873	How write event for drawed shape?	public Form1()\n        {\n            InitializeComponent();\n            Rectangle rect = new Rectangle(0, 0, 100, 200);\n            Click += Form1_Click;\n        }\n//associate this method to Click event Form\n     private void Form1_Click(object sender, EventArgs e)\n        {\n            Rectangle rect = new Rectangle(0, 0, 200, 100);\n            Point cursorPos = this.PointToClient(Cursor.Position);\n            //you are in rectangle so message display\n            if (rect.Contains(cursorPos))\n            {                \n                MessageBox.Show("in");\n            }\n\n        }	0
10822316	10818638	Replicating ContextMenu constructor in ContextMenuStrip	ToolStripItem[] newItems = {\n                    new ToolStripMenuItem("All", null, DoThis),\n                    new ToolStripMenuItem("Text", null, DoThis)\n                };\n\nthis.contextMenuStrip1.Items.Add(new ToolStripMenuItem("Clear", null, newItems) {Name="Clear"});\n\nvar clearItem = this.contextMenuStrip1.Items["Clear"] as ToolStripMenuItem;	0
1978827	1978821	How to reset a Dictionary	aDict.Clear();	0
19882836	19882766	How to import GetAsyncKeyState in C#?	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\n// not here\n\nnamespace WindowsFormsApplication1\n{\n\n    // not here\n\n    public partial class Form1 : Form\n    {\n\n        // put it INSIDE the class\n\n        [DllImport("user32.dll")]\n        public static extern short GetAsyncKeyState(int vKey);\n\n        public Form1()\n        {\n\n            // not inside methods, though\n\n            InitializeComponent();\n        }\n\n    }\n\n}	0
17301331	17299619	Get URL Variables from a Frame and Pass to Codebehind	protected void Page_Load(object sender, EventArgs e)\n{\n\n    if (!IsPostBack)\n    {\n        string frameURL = Request.UrlReferrer.ToString() ?? "NO DATA";\n\n        if ((frameURL != null) && (frameURL != "NO DATA"))\n        {\n\n            Uri frameURI = new Uri(frameURL);\n\n            NameValueCollection queryVars = HttpUtility.ParseQueryString(frameURI.Query);\n\n            //If this is in Orion, we want to change the canceller to standby if it's 97, not 96\n            if (queryVars["NetObject"] == "N:97" || queryVars["NetObject"] == "N%3a97")\n            {\n                SelectCanceller.SelectedValue = "Standby";\n                primaryStandby = false;\n            }\n        }	0
2739415	2739337	condition in recursion - best practise	Child Find(Parent parent, object criteria)\n    {\n        return parent.Childs.Select(        // Loop through the children looking for those that match the following criteria\n            c => c.Match(criteria)          // Does this child match the criteria?\n                ? c                         // If so, just return this child\n                : this.Find(c, criteria)    // If not, try to find it in this child's children\n        ).FirstOrDefault();                 // We're only interested in the first child that matches the criteria or null if none found\n    }	0
22427958	22426430	Updating Multiple PictureBoxes from multiple threads	// this is called from any thread\npublic void videoImage(Image image)\n{\n    // are we called from the UI thread?\n    if (this.InvokeRequired)\n    {\n        // no, so call this method again but this\n        // time use the UI thread!\n        // the heavy-lifting for switching to the ui-thread\n        // is done for you\n        this.Invoke(new MethodInvoker(delegate { videoImage(image); }));\n    }\n    // we are now for sure on the UI thread\n    // so update the image\n    this.VideoViewer.Image = image;\n}	0
10324533	10324507	Get contents of enum to a dropdownlist	myPageViewModel.ColourList = Enum.GetNames(typeof(Colors))\n    .Select(c => new SelectListItem() { Text = c, Value = c })\n    .ToArray();	0
13017393	13017377	Generics in C# with OleDbConnection	public class DatabaseConnector<TConnection> where TConnection : DbConnection, new() {	0
26619072	26618839	Text changed event of textBox object: how to perform text change + another action	private void textBox1_TextChanged(object sender, EventArgs e)\n{\n    this.textBox2.TextChanged -= textBox2_TextChanged;\n    this.textBox2.Text = "";\n    this.textBox2.TextChanged += textBox2_TextChanged;\n}\n\nprivate void textBox2_TextChanged(object sender, EventArgs e)\n{\n    this.textBox1.TextChanged -= textBox1_TextChanged;\n    this.textBox1.Text = "";\n    this.textBox1.TextChanged += textBox1_TextChanged;\n}	0
22072505	22066826	Set composite key on table with only One-to???Zero-or-One relations	.WithMany().HasForeignKey(..)	0
21077192	21076892	How to add a Canvas event from another class? WPF C#	var mainWindowInstant = (MainWindow)App.Current.MainWindow;\nmainWindowInstant.Getcanvas.MouseMove += new MouseEventHandler(...);	0
21755055	21751143	How to extract attribute value of a method within an unreferenced assembly	foreach (var x in attrs)\n{\n    var attributeType = x.GetType();\n    if (attributeType.FullName == "ClassLibrary1.IDAttribute") // also check for attributeType.Assembly == loaded assembly, if needed \n    {\n        var id = (int)attributeType.GetProperty("ID").GetValue(x);\n        Console.WriteLine(id);\n    }\n}	0
4222019	4221999	In a Generic Provider how to find and edit properties of T? (C#)	public class Provider<T> where T : ICommonInterface	0
24589682	24588545	How to ignore a Foreign Key restriction on delete?	DELETE FROM Ficheros\nWHERE IDFichero IN (27, 28, ...)\n  AND NOT EXISTS (SELECT 1\n                  FROM ChildTable\n                  WHERE ChildTable.IDFichero = Ficheros.IDFichero)	0
6281449	6281418	How can I navigate from a variable using webbrowser.navigate()?	string site = "page.php";\nwebBrowser1.Navigate("http://www.example.com/" + site);	0
18264966	18264892	Regex: ignore whitespace between fields	\s(?=\w+:)	0
2477537	2477365	How do I differentiate between different descendents with the same name?	IEnumerable<RunDetail> runDetails = from run in xdocument.Descendants("run")\n                                select new RunDetail\n                                {\n                                    Name = run.Element("name").Value,\n                                    Date = int.Parse(run.Element("date").Value)\n                                };	0
33274336	33274209	CSV file Missing Row Separator , how to read it in c #?	string[] readText = File.ReadAllLines(path);\n\nfor (int i=0;i<readText.length;i++)\n{\n    readText[i]=readText[i].Trim([',']);\n}\n\nFile.WriteAllLines(path, readText);	0
24715106	24714947	Stream TextReader to a File	using (var textReader = File.OpenText("input.txt"))\nusing (var writer = File.CreateText("output.txt"))\n{\n    do\n    {\n        string line = textReader.ReadLine();\n        writer.WriteLine(line);\n    } while (!textReader.EndOfStream);\n}	0
21313273	21304454	How to stop Excel-DNA function from calculating while inputting values	public static object SlowFunction()\n{\n    if (ExcelDnaUtil.IsInFunctionWizard()) return "!!! In Function\nWizard";\n\n    // do the real work....\n}	0
30058769	30058380	Combining information from two lists	var combined = passed\n    .Concat(failed)\n    .GroupBy(x => x.DataDate)\n    .Select(x => new ReportData {\n        DataDate = x.Key,\n        quantity = x.Sum(rd => rd.quantity),\n        rejected = x.Sum(rd => rd.rejected),\n        cumulativeQuantity = x.Max(rd => rd.cumulativeQuantity), // or Sum\n        cumulativeRejected = x.Max(rd => rd.cumulativeRejected)  // or Sum\n    }).ToList();\n\n// Fill "holes" for dates not present in both lists.\nfor (var i = 1; i < combined.Count; i++)\n{\n    if (combined[i].cumulativeQuantity == 0)\n        combined[i].cumulativeQuantity = combined[i - 1].cumulativeQuantity;\n    if (combined[i].cumulativeRejected == 0)\n        combined[i].cumulativeRejected = combined[i - 1].cumulativeRejected;\n}	0
4360903	4360839	Encrypt cookies in ASP.NET	private static void SetEncryptedCookie(string name, string value)\n{\n    var encryptName = SomeEncryptionMethod(name);\n    Response.Cookies[encryptName].Value = SomeEncryptionMethod(value);\n    //set other cookie properties here, expiry &c.\n    //Response.Cookies[encryptName].Expires = ...\n}\n\nprivate static string GetEncryptedCookie(string name)\n{\n    //you'll want some checks/exception handling around this\n    return SomeDecryptionMethod(\n               Response.Cookies[SomeDecryptionMethod(name)].Value);\n}	0
1909835	1909768	Nhibernate DetachedCriteria: Find entities where a property's property match a value	DetachedCriteria.For<User>().AddAlias("Credentials", "Credentials").Add(Expression.Eq("Credentials.UserName", "someuser");	0
3623788	3623777	Using session variable with ASP.Net membership provider	Membership.GetUser().ProviderUserKey	0
2910985	2910930	Return multiple values with stream	public Dictionary<string, Stream> GetData(string[] paths)\n{\n    Dictionary<string, Stream> data = new Dictionary<string, Stream>();\n    foreach (string path in paths)\n    {\n        data[path] = new FileStream(path, FileMode.Open);       \n    }\n\n    return data;\n}	0
9064843	9064727	C# storing text in SQL Server for full text search	Encoding.UTF8.GetBytes()	0
5864292	5864277	Parse array string to array object in Javascript	var responseArray = JSON.parse( result.d )\n//responseObject is now a literal javascript array, so you can iterate over it as you would any other array	0
10655669	10655263	Set Fan Speed in C#	[DllImport("Cimwin32.dll")]\nstatic extern uint32 SetSpeed(in uint64 sp);\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n           SetSpeed(300);\n}	0
33351875	33350094	how to Get X and Y coordinates of user touch relative to screen with C# in windows 10 universal	private void _theCanvas_Tapped(object sender, TappedRoutedEventArgs e)\n    {\n        _pointerDeviceType.Text = e.PointerDeviceType.ToString();\n        var position = e.GetPosition(_root);\n        _x.Text = position.X.ToString();\n        _y.Text = position.Y.ToString();\n    }	0
24548042	24547714	Insert user defined variables in to the sql statements	var mybtncmd2 = new SqlCommand("SELECT StraightDist FROM StraightLineDistances WHERE FirstCity=@City1 AND SecondCity=@City2;", mybtnconn2);\nmybtncmd2.Parameters.AddWithValue("@City1", "007");\nmybtncmd2.Parameters.AddWithValue("@City2", "017");	0
14447556	14404621	StatusCodes for IOperationResult in Couchbase	Memcached Binary Protocol	0
2972371	2972077	Multiline text as the button label in Windows Forms	btnOK.Text = "OK" + Environment.NewLine + "true";	0
4779789	4779783	How to convert a ListItemCollection into a ListItem[]?	var result = rank.Cast<ListItem>().ToArray();	0
2016504	2016463	How to assign a character using ASCII data?	'\u001C'	0
10863702	10863141	asp.net popup confirmation window	return confirm("Are you sure you want to delete this user?");	0
27675593	27601687	How to check if a property is decorated with a custom attribute using Roslyn?	foreach (var attribute in node.AttributeLists.SelectMany(al => al.Attributes))\n            {\n                if (csFile.FileSemanticModel.GetTypeInfo(attribute).Type.ToDisplayString() == "Proj.Attributes.ValidationAttribute")\n                {\n                    var arg = attribute.ArgumentList.Arguments.FirstOrDefault(aa => aa.NameEquals.Name.Identifier.Text == "IsJDate");\n                    if (arg != null && arg.Expression.IsKind(SyntaxKind.TrueLiteralExpression))\n                        validationKind = ValidationKind.JDate;\n                }\n            }	0
17941061	17939713	Comparing Ip value for determine whether a specific range	int[] maxIP = new int[] { 10, 255, 15, 30 };\n    int[] minIP = new int[] { 10, 100, 12, 21 };\n    char[] sep = new char[] { '.' };\n\n    var ip = "10.100.16.21";\n\n    string[] splitted = ip.Split(sep);\n\n    for (int i = 0; i < splitted.Length; i++)\n    {\n        if (int.Parse(splitted[i]) > maxIP[i])\n        {\n            Console.WriteLine("IP greather than max");\n            break;\n        }\n        else if (int.Parse(splitted[i]) < minIP[i])\n        {\n            Console.WriteLine("IP less than min");\n            break;\n        }\n    }	0
13305437	13239539	Read in a file using a regular expression?	foreach(var filePath in logpath)\n{\n    var sbRecord = new StringBuilder();\n    using(var reader = new StreamReader(filePath))\n    {\n        do\n        {\n            var line = reader.ReadLine();\n            // check start of the new record lines\n            if (Regex.Match(line, datePattern) && sbRecord.Length > 0)\n            {\n                // your method for log record\n                HandleRecord(sbRecord.ToString());\n                sbRecord.Clear();\n                sbRecord.AppendLine(line);\n            }\n            // if no lines were added or datePattern didn't hit\n            // append info about current record\n            else\n            {\n                sbRecord.AppendLine(line);\n            }\n        } while (!reader.EndOfStream)\n    }\n}	0
27823525	27823378	Setup Mock for generic function with generic Lambda using Moq It.IsAny	var _menagerMock = new Mock<IManager>();\n        _menagerMock.Setup(x => x.GetOrAdd("stringValue",\n            It.IsAny<Func<Tuple<int>, string>>(), It.IsAny<Tuple<int>>()));	0
7569222	7568845	Retrieve comboBox displayed values	string displayedText;\n        DataRowView drw = null;\n\n        foreach (var item in comboBox1.Items)\n        {\n            drw = item as DataRowView;\n            displayedText = null;\n\n            if (drw != null)\n            {\n                displayedText = drw[comboBox1.DisplayMember].ToString();\n            }\n            else if (item is string)\n            {\n                displayedText = item.ToString();\n            }\n        }	0
13397342	13397301	How to set code behind properties in javascript	var <%=DateFormat%> = "dd-mm-YYYY";	0
9758379	9758273	Parse xml using c#	XElement input = XElement.Load(filename);\nforeach(XElement feedChild in input.Elements("feed"))\n  foreach(XElement linkChild in feedChild.Elements("link"))	0
9581709	9581626	Show row number in row header of a DataGridView	row.HeaderCell.Value = String.Format("{0}", row.Index + 1);	0
3098723	3098698	How do you set the initial state of a checkbox in WPF (either in XAML or code)?	IsChecked="True"	0
27415392	27415391	Display Yandex map in Windows Phone 8.1 Application	MyMap.Style = MapStyle.None;\nHttpMapTileDataSource dataSource = new HttpMapTileDataSource("http://vec02.maps.yandex.net/tiles?l=map&v=2.2.3&x={x}&y={y}&z={zoomlevel}");\nMapTileSource tileSource = new MapTileSource(dataSource);\ntileSource.Layer = MapTileLayer.BackgroundReplacement;\nMyMap.TileSources.Add(tileSource);	0
16556313	16556217	How to exclude a record from the Drop Down List	var selectList = new SelectList((from s in statList.ToList() where s.Name != "Cancelled" select new { statusId = s.Id, statusName = s.Name }), "statusId", "statusName")	0
1990176	1989986	Grayscale printing in Word 2007 from C#	public bool setPrinterToGrayScale(string printerName) \n{\n  short monochroom = 1;\n  dm = this.GetPrinterSettings(printerName);\n  dm.dmColor = monochroom;\n\n  Marshal.StructureToPtr(dm, yDevModeData, true);\n  pinfo.pDevMode = yDevModeData;\n  pinfo.pSecurityDescriptor = IntPtr.Zero;\n\n  Marshal.StructureToPtr(pinfo, ptrPrinterInfo, true);\n  lastError = Marshal.GetLastWin32Error();\n\n  nRet = Convert.ToInt16(SetPrinter(hPrinter, 2, ptrPrinterInfo, 0));\n  if (nRet == 0)\n  {\n    //Unable to set shared printer settings.\n\n    lastError = Marshal.GetLastWin32Error();\n    //string myErrMsg = GetErrorMessage(lastError);\n\n    throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());\n\n   }\n   if (hPrinter != IntPtr.Zero)\n      ClosePrinter(hPrinter);\n    return Convert.ToBoolean(nRet);\n}	0
5417860	5408781	NHibernate using QueryOver with WHERE IN	var qOver = _HibSession.QueryOver<MyModel>(() => baseModel)\n    .JoinAlias(() => baseModel.Submodels, () => subModels)\n    .Where(Restrictions.In(subModels.ID,IDsSubModels))\n    .List<MyModel>();	0
29284277	29224905	PowerShell Output Formatting from C# using DefaultDisplayPropertySet	using System.Management.Automation;\npublic class Whatever {\n   public string One { get { return "This is one"; } }\n   public string Two { get { return "This is two"; } }\n   public string Three { get { return "This is three"; } }\n   public string Four { get { return "This is four"; } }\n\n   public static PSObject Get() {\n\n      var w = new Whatever();\n      var pso = new PSObject(w);\n      var display = new PSPropertySet("DefaultDisplayPropertySet",new []{"One","Two"});\n      var mi = new PSMemberSet("PSStandardMembers", new[]{display});\n      pso.Members.Add(mi);\n\n      return pso;\n   }\n}	0
14049837	14043122	Is there a way to disable Default Endpoint in ServiceStack?	Plugins.RemoveAll(x => x is PredefinedRoutesFeature);	0
30290505	30289994	SQL INSERT from two tables	INSERT INTO Task (Employee_ID, Project_Id, Assigned_Project_Name)\nSELECT e.Employee_Id , p.Project_Id, 'NewTask'\nFROM Employees e INNER JOIN Projects p \nWHERE e.last_name='XYZ' AND e.first_name='ABC' \nAND p.Project_Name='SomeProject';	0
10566337	10198458	Get selectedvalues of multi-select list box	foreach(int blah in multilistbox.SelectedIndices){\n\n  MessageBox.Show(blah.ToString());\n\n  }	0
8819274	8819201	passing this as parameter in static method	var timeLine = new Timeline();\ntimeLine.MethodTwo();	0
25296263	25271017	gridding extraction in image	Image img = Image.FromFile(yourImage);\nBitmap bmp = new Bitmap(img.Width, img.Height);\n\nusing (Graphics G = Graphics.FromImage(bmp) )\nusing (Pen pen = new Pen(Color.DarkBlue, 2f) )\n{\n    G.Clear(Color.Black);\n    for (int x = 6; x  < img.Width; x += 43)\n        G.DrawLine(pen, x, 0, x, img.Height);\n    for (int y = 10; y  < img.Height; y += 43)\n        G.DrawLine(pen, 0, y, img.Width, y);\n}\nbmp.Save(yourGrid);\nbmp.Dispose();\nimg.Dispose();	0
13529538	13526329	How to query Users/Recipients sharing Contacts/Calendars with Current Outlook User?	ContactsModule module = (ContactsModule)outlookObj.ActiveExplorer().NavigationPane.Modules.GetNavigationModule(OlNavigationModuleType.olModuleContacts);\nforeach (NavigationGroup navigationGroup in module.NavigationGroups) {\n     foreach (NavigationFolder navigationFolder in navigationGroup.NavigationFolders) {\n          foreach (var item in navigationFolder.Folder.Items) {\n                     // Found Folders are: Contacts, Suggested Contacts and Shared Contact Folders\n\n\n                     // Import/Read ContactItems\n                     ...\n                }	0
22459787	22459679	Force inherited class to call a base helper method	class A\n{\n   void MethodOne()\n   {\n      //Here you perform your obligatory logic.\n\n      //Then, call the overridable logic.\n      MethodOneCore();\n   }\n\n   virtual void MethodOneCore()\n   {\n      //Here you perform overridable logic.\n   }\n}\n\nclass B: A\n{\n   override void MethodOneCore()\n   {\n      //Here you override the "core" logic, while keeping the obligatory logic intact.\n   }\n}	0
31925149	31923872	Displaying only first row from datagridview	DataView view = new DataView(ds.Tables[0]);\nDataTable distinctInvoiceNumbers = view.ToTable(true, "invoiceno");\n//clear datagrid rows here\n DataTable dt=new Datatable();\n dt = ds.Tables[0].Clone();\n int index=0;// zero if first is clicked, increase index for each next button click\n foreach(datarow dr in ds.Tables[0].Rows)\n  {\n   if(distinctInvoiceNumbers.Rows[0][index].ToString()==dr[0].ToString())\n    {\n      dt.ImportRow(dr);//add matching rows to datatable\n    }\n  }\n  datagridview1.DataSource=dt;	0
10298839	10177548	Telerik RadChart "Input string was not in a correct format"	...\n this.trcResults.DataBinding += this.trcResults_DataBinding;\n this.trcResults.BeforeLayout += this.trcResults_BeforeLayout;\n this.trcResults.DataSource = pcl;\n this.trcResults.DataBind();\n}\n\nvoid trcResults_DataBinding(object sender, EventArgs e)\n{\n var senderChart = (RadChart)sender;\n var pcl = senderChart.DataSource as IEnumerable<PollContainer>;\n\n foreach (var pollContainer in pcl)\n {\n  // prepend a sentinel symbol\n  pollContainer.AnswerText = "x" + pollContainer.AnswerText;\n }\n}\n\n\nvoid trcResults_BeforeLayout(object sender, EventArgs e)\n{\n foreach (var axisItem in this.trcResults.PlotArea.XAxis.Items)\n {\n  // remove the sentinel symbol\n  axisItem.TextBlock.Text = axisItem.TextBlock.Text.Remove(0, 1);\n }\n}	0
24594402	24594288	recognize if program was run from Desktop	string path = Directory.GetCurrentDirectory();\nstring desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);\nif (!path.Equals(desktopPath))\n{\n    Console.WriteLine("file is not at desktop");\n}	0
13262018	13261997	Launch processes one after another in C#	Process.WaitForExit()	0
2990862	2990635	Client App with WCF to consume ASMX	using (LatestServiceSoapClient proxy = new LatestServiceSoapClient("LatestServiceSoap"))\n{\n    label1.Text = proxy.Welcome();\n}	0
9746964	9746849	Batch update with hardcoded set	UPDATE\n    Table\nSET\n    Table.col1 = other_table.col1,\n    Table.col2 = other_table.col2\nFROM\n    Table\nINNER JOIN\n    other_table\nON\n    Table.id = other_table.id	0
13936410	13936008	c# - DotNetZip open zip file from MemoryStream	public ActionResult Index()\n{\n    var memoryStream = new MemoryStream();\n\n    using (var zip = new ZipFile())\n    {\n        zip.AddFile("ReadMe.txt");\n        zip.AddFile("7440-N49th.png");\n        zip.AddFile("2008_Annual_Report.pdf"); \n        zip.Save(memoryStream);\n    }\n\n    memoryStream.Seek(0, 0);\n    return File(memoryStream, "application/octet-stream", "archive.zip");\n}	0
10494681	10494629	Launching Webcam in Metro style apps	using Windows.Media.Capture;\n\nvar ui = new CameraCaptureUI();\nui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);\nvar file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);\n\nif (file != null) \n{\n   var bitmap = new BitmapImage();\n   bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));\n   Photo.Source = bitmap;\n}	0
18075212	18075037	Add custom attribute to an HTML input element with C#	chkBx.InputAttributes.Add("itemname", strtemPath);	0
7482800	7482552	How do I get a dataset result for multiple conditions in C#	Select("name = '" + tbxName.Text + "' AND account = '" +tbx.Account +"'")	0
9824549	9824276	How to remove the "\r\t\t" escape characters from XmlReader	var readerSettings = new XmlReaderSettings\n{\n    IgnoreWhitespace = true,\n};\n\nusing (XmlReader reader = XmlReader.Create(new FileStream(archivePath, FileMode.Open), readerSettings))\n{\n    //...\n}	0
10793344	10793278	Implementing a waiting routine inside a timer_elapsed event	**BackgroundWorker_DoWork event**\nint nTrials = 0; // this method will help you pick any number of trials before launching the applicaion\nbool isRunning = false;\nwhile((isRunning = Process.GetProcessesByName("notepad") == 0)  || nTrials < 2)\n{\n    Thread.Sleep(1000); // w8 1 second before queriying the process name\n    nTrials++;\n} \n\nif ( isRunning ) RunProcess();	0
4739791	4739708	Using Streams in C#	...\n\nStream ReceiveStream = myWebResponse.GetResponseStream();\n\n    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");\n\n        // Pipe the stream to a higher level stream reader with the required encoding format. \n     StreamReader readStream = new StreamReader( ReceiveStream, encode );\n     Console.WriteLine("\nResponse stream received");\n     Char[] read = new Char[256];\n\n        // Read 256 charcters at a time.    \n     int count = readStream.Read( read, 0, 256 );\n        Console.WriteLine("HTML...\r\n");\n\n    while (count > 0) \n    {\n            // Dump the 256 characters on a string and display the string onto the console.\n        String str = new String(read, 0, count);\n        Console.Write(str);\n        count = readStream.Read(read, 0, 256);\n    }\n\n...	0
25093293	25082089	Make a phonecall ios xamarin	public void UpdateCell (string subtitle2)\n{\n    //Makes a new NSUrl\n    var callURL = new NSUrl("tel:" + subtitle2);\n\n    call.SetTitle(subtitle2, UIControlState.Normal);\n    call.TouchUpInside += (object sender, EventArgs e) => {\n    if (UIApplication.SharedApplication.CanOpenUrl (callURL)) {\n    //After checking if phone can open NSUrl, it either opens the URL or outputs to the console.\n\n        UIApplication.SharedApplication.OpenUrl(callURL);\n    } else {\n    //OUTPUT to console\n\n    Console.WriteLine("Can't make call");\n    }\n  };          \n}	0
8476606	8476378	How To Improve Filter Speed in ObservableCollection	bool found = host.Hostname.ToLower().Contains(searchBox.Text.ToLower());             \nif (!found)\n{\n  found = host.IP.ToString().Contains(searchBox.Text.ToLower());\n  if (!found)\n  {\n    found = host.Username.ToString().Contains(searchBox.Text.ToLower()); \n  }\n}	0
2337529	2337515	Using enum as integer constant in C#	class InputManager<T>\n{\n   SortedDictionary<T,Keys> inputList = new SortedDictionary<T,Keys>();  \n\n   public void add(T id, Keys key) {...}  \n   public bool isPressed(T id) {...}    \n}	0
20245407	20245130	How to convert an Enum which is a generic parameter to another Enum?	( BasicEnum )Enum.ToObject( typeof( BasicEnum ), someEnum )	0
7421883	7420524	NHibernate 3 specify sql data type with loquacious syntax	ca.Property(x => x.Code, map =>\n{\n    map.Type(NHibernateUtil.AnsiString);\n    map.Column(/*etc.*/); \n});	0
3095963	3095781	How to use SQL 'LIKE' with LINQ to Entities?	var people = entities.People.Where("it.Name LIKE @searchTerm", new ObjectParameter("searchTerm", searchTerm));	0
27679505	27678459	Change the NavigationFrame Content on Button Click in WPF	Frame1.Navigate(new Page1());	0
26040369	26040280	Cannot retrieve multiple values from a listbox c#	List<FILE_REPORT_TYPES> mySelectedList = new List<FILE_REPORT_TYPES>();\nforeach (Object selectedItem in ListBox.SelectedItems)\n{\n    mySelectedList.Add( ((FILE_REPORT_TYPES)selectedItem) );\n}	0
3919553	3919541	Add Date & Time and Convert to UTC	DateTime date3 = date1.Date + date2.TimeOfDay;	0
3574285	3574250	add all keys in a dictionary <int, string> in c#	D.Keys.Sum();	0
34346163	34336431	How to shorten Odata query string?	POST /Policy/SomeNamespace.GetSubsetByPolicyNumber\n{ "PolicyNumbers": [ 123, 456, ... ] }	0
7749943	7749373	How can I get background color of a selected item in checkboxlist	foreach (ListItem  item in cbFilter.Items   )\n            {\n                if (item.Selected)\n                {\n                    Response.Write(item.Attributes.CssStyle["background-color"].ToString());\n                }\n            }	0
25065058	25064454	How to not block main UI thread from a worker thread while working with a large global object on the main thread	internal static class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    [STAThread]            // <= I needed to add this attribute\n    private static void Main()\n    {\n       //...\n    }\n}\n\n\n\n\npublic partial class MainForm : Form () \n{    \n    // you can call this in the InitializeComponents() for instance\n    void someMethodInYourFormIERunningOnTheUIThread()\n    {\n        ScanLib scanLib  = null;\n        var th = new Thread(() =>\n        {\n            scanLib = new ScanLib();\n        });\n        th.SetApartmentState(ApartmentState.MTA); // <== this prevented binding the UI thread for some operations\n        th.Start();\n        th.Join();\n        this.scanLibraryReference = scanLib;\n    }\n    //...\n}	0
14838883	14838785	Check if a line of XML is valid (not a full document)	public static bool IsValid(this string XML)\n{\n    try\n    {\n        XElement temp = XElement.Parse(XML);\n    }\n    catch (FormatException)\n    {\n        return false;\n    }\n    catch (XmlException)\n    {\n        return false;\n    }\n    return true;\n}	0
28476735	28476164	how to search table through textbox?	private void searchbtn_Click(object sender, EventArgs e)\n{\n     SqlCeConnection con = new SqlCeConnection(@"Data Source=C:\Users\hry\Documents\Visual Studio 2010\Projects\Kargozini\Kargozini\khadamat.sdf");\n\n     try\n     {\n         con.Open();\n         string SearchQuerry = "SELECT ID, radif, Name, Type, Description, Price FROM Users WHERE ID = '"+searchtxt.Text+"'" ;\n         SqlCeCommand com = new SqlCeCommand(SearchQuerry,con);\n\n         SqlCeDataReader sqlReader = com.ExecuteReader();\n\n         while (sqlReader.Read())\n        {\n            txtID.text = sqlReader.GetValue(0).ToString();\n            txtRadif.text = sqlReader.GetValue(1).ToString();\n            txtName.text = sqlReader.GetValue(2).ToString();\n        }\n\n        sqlReader.Close();\n        com.Dispose();\n        con.Close();\n     }\n     catch (SqlCeException ex)\n     {\n         MessageBox.Show(ex.Message);\n     }\n}	0
24314721	24314677	Generating a unique primary key	System.Guid.NewGuid().ToString();	0
16943409	16943352	How use Class generated by XSD	using (var stream = new FileStream(xmlFilePath))\n{\n     var serializer = new XmlSerializer(typeof(body));\n     var body = (body) serializer.Deserialize(stream);\n }	0
5341351	5340864	How to consume VB6 DLL from .NET?	int[] vectorOfIntegers = new int[5];\nvectorOfIntegers[0] = 123;\nvectorOfIntegers[1] = 456;\n.\n:\nint[] outputArray = cls.MyFunctionInClass(vectorOfIntegers);	0
24095093	24094778	Can not parse the string to Exact DateTime in C#	string givenDate = ("2013-03-05T08:28:18+0000");\nDateTime d = DateTime.Parse(givenDate, System.Globalization.CultureInfo.InvariantCulture);\nstring ouputDate = d.ToUniversalTime().ToString("MMM d, yyyy h:m:s tt",  System.Globalization.CultureInfo.InvariantCulture);	0
11957534	11957327	Lambda implementation for OR expression concatenation	Colors currentValidColors = 0;\ncolorStr.Split(new char[] { ',' })\n.Select(p => EnumHelper.GetEnumFromString<Colors>(p))\n.ToList()\n.ForEach(c => currentValidColors |= c);	0
25137550	25124298	How to progammatically configure the web.config of a website installed in IIS?	string[] file = Directory.GetFiles(myWebsite.physicalPath, "*config");\nif (file != null)\n{\n    XmlDocument doc = new XmlDocument();\n    doc.Load(file[1]);\n    XmlNodeList configurationStrings = doc.SelectNodes("/configuration/connectionStrings/add");\n    configurationStrings[0].Attributes["connectionString"].Value = ".\\SQLEXPRESS;Database=_usr;Integrated Security=true";\n    configurationStrings[1].Attributes["connectionString"].Value = ".\\SQLEXPRESS;Database=_main;Integrated Security=true";\n    configurationStrings[2].Attributes["connectionString"].Value = ".\\SQLEXPRESS;Database=_activity;Integrated Security=true";\n    doc.Save(file[1]);\n}	0
11676376	11676215	Find and Replace XML file	new Regex("web/[0-9]+/").Replace(youxmlstr, "web2/1/");	0
15886440	15886368	How to set multiple integer ReportParameter in c#?	MyReportViewer.ServerReport.SetParameters(\n    new ReportParameter("storeSelected", new string[] { "2", "3", "4" }, false)\n);	0
16877701	16877619	How c# handles JSON object similiar to javascript without define object class before parsing	string jsonString = "{\"status\" : \"true\"}";\ndynamic dyn = JsonConvert.DeserializeObject<dynamic>(jsonString);\nConsole.WriteLine(dyn.status); //prints true	0
6853543	6853517	DateTime format string pattern	DateTime dateValue = DateTime.Parse("7/28/2011 09:00:03 AM");\nstring formattedString;\nif (dateValue.Minute == 0)\n    formattedString = dateValue.ToString(@"M/d/yyyy Htt");\nelse\n    formattedString = dateValue.ToString(@"M/d/yyyy H:mmtt");	0
33174412	33173739	Converting value object into correct RegistryValueKind	dontAskOptions.SetValue(\n    "IDS_WARN_GENERAL_WINXP_EOL", \n    unchecked((int) 0xffffffff), \n    RegistryValueKind.DWord);	0
7565989	7565415	Edit text in C# console application?	static void Main(string[] args)\n{\n    Console.Write("Your editable text:");\n    SendKeys.SendWait("hello"); //hello text will be editable :)\n    Console.ReadLine();\n}	0
23225418	23225320	How to check if slideshow is running	MsoTriState.msoTrue	0
17289345	17289160	Group time by X minutes, splitting at X minute intervals	times.GroupBy(y => (int)(y.Ticks / TimeSpan.TicksPerMinute / 5))	0
6019373	6019325	C# - EF4 - Get the server's DateTime.Now	DateTime ServerDate = Entities.CreateQuery<DateTime>("CurrentDateTime()").AsEnumerable().First();	0
26077317	26077250	Trying to run multiple async task in a c# console application	static async void Main(string[] args)\n{\n    var url = System.Configuration.ConfigurationManager.AppSettings["CentrisURL"];\n\n    if (url == null)\n    {\n        Console.WriteLine("Failed to load API url");\n    }\n\n    var client = new HttpClient();\n    client.BaseAddress = new Uri(url);\n    client.DefaultRequestHeaders.Accept.Clear();\n    client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/xml"));\n\n    await Task.WhenAll(\n        new Task[] {\n            DbRequestHandler.ReadRooms(client),\n            DbRequestHandler.ReadRoomsType(client),\n            DbRequestHandler.ReadCourses(client),\n            DbRequestHandler.ReadTeachers(client),\n        }\n    );\n}	0
24219017	24085275	How to get friends that are in a Contact List?	private void button1_Click(object sender, EventArgs e)\n    {\n        ArrayList UserList = new ArrayList();\n        var SkypeClient = new SKYPE4COMLib.Skype();\n        foreach(SKYPE4COMLib.Group Group in SkypeClient.CustomGroups)\n        {\n                if (Group.DisplayName == "<specify the usergroup name here>")\n                {\n                    foreach (SKYPE4COMLib.User User in Group.Users)\n                    {\n                        //Adds the usernames from the specified group in the list.\n                        UserList.Add(User.Handle);\n                    }\n                }\n        }\n\n        //Writing the list in a label\n        string s = "";\n        foreach(string str in UserList)\n        {\n            s = s + str + Environment.NewLine;\n        }\n        label1.Text = s;\n    }	0
1468987	1468714	Generics, Inheritance, and Casting	public interface ITypeA<out T> {}\n\npublic class TypeA<T> : ITypeA<T> {}\n\npublic class TypeB<T> {}\n\npublic class TypeC : TypeB<int> {}\n\nclass Program\n{\n    public static void MyMethod<OutputType>(ITypeA<TypeB<OutputType>> Parameter) {}\n\n    static void Main(string[] args)\n    {\n        ITypeA<TypeC> Test = new TypeA<TypeC>();\n        MyMethod<int>(Test);\n    }\n}	0
3135491	3135314	Simply Removing A Curve?	Pane.CurveList[ Pane.CurveList.Count - 1  ].Clear();\nzgc.Refresh();	0
31331879	31331805	How to turn a list of values from a rich textbox to formatted list C#	string result = "(" + string.Join(",", textBox.Text.Split(new[] { "\r\n", "\n" }, StringSplitOptions.RemoveEmptyEntries).Select(s => "'" + s + "'")) + ")";	0
23443332	23440719	Cannot insert hard coded values to sqlite in wp7	cmd.ExecuteNonQuery();	0
5147355	5147298	C#. Fastest Regex to match any string	class FastestRegex\n{\n    public static readonly Regex RE = new Regex("", RegexOptions.Compiled);\n}	0
7896542	7877332	Delete rows from data base table	foreach (var item in deleteUserActivities)\n{\n     m_WeightScaleEntities.DeleteObject(item);\n}\nAnd then SaveChanges() on the object context.	0
8378374	8375593	C# post file to server	myWebClient.Headers.Add("Content-Type", "audio/x-flac; rate=16000");	0
31085765	31041482	Cropping a JPG without loading all of it in memory	jpegtran -crop WxH+X+Y input_file output_file	0
34321061	34319263	Return a list of all Active Directory groups a user belongs to in string[ ]	using System.DirectoryServices.AccountManagement;\n\npublic static string[] GetGroups(string username)\n{\n    string[] output = null;\n\n    using (var ctx = new PrincipalContext(ContextType.Domain))\n    using (var user = UserPrincipal.FindByIdentity(ctx, username))\n    {\n        if (user != null)\n        {\n            output = user.GetGroups() //this returns a collection of principal objects\n                .Select(x => x.SamAccountName) // select the name.  you may change this to choose the display name or whatever you want\n                .ToArray(); // convert to string array\n        }\n    }\n\n    return output;\n}	0
7280099	7279879	How i can use two optional object in c# when one of them is required?	class MyClass : IValidatableObject\n{\n   public string EId {get;set;}\n   public string PId {get;set;}\n\n   public IEnumerable<ValidationResult> Validate(ValidationContext vC)\n   {\n      if (string.IsNullOrEmpty(EId) && string.IsNullOrEmpty(PId))\n         yield return new ValidationResult("one of EId or PId must be set!", new []{ "EId", "PId" });\n   }\n\n}	0
33594648	33594502	How to place text between two html tags in C#	private void boldText_Click(object sender, EventArgs e)\n{\n    textArea.SelectedText = string.Format("<b>{0}</b>", textArea.SelectedText); \n    textArea.SelectionLength = 0;\n}	0
1678261	1678249	C# Array of Buttons	List<Button> listOfButtons = new List<Button>();\nlistOfButtons.Add(yourButton);	0
22842658	22842629	Only allow multiples of 10s from the user	if(userInput % 10 == 0)\n{\n    //valid\n}	0
2726468	2726448	How do I respond to a specific sequence of key presses?	if (e.KeyCode == neededLetter as Keys)\n{\n    if ( neededLetter == "n" )\n    {\n        neededLetter = "o";\n    } else if ( neededLetter == "o" ) {\n        neededLetter = "t";\n    } else if ( neededLetter == "t" ) {\n        neededLetter = "e";\n    } else if ( neededLetter == "e" ) {\n        // you now have the full sequence typed, show your app\n    }\n} else { // not sure if this is valid, but it's the idea\n    neededLetter = "n"; // reset the sequence if another letter is typed\n}	0
24949140	24946575	Passing Data from Page to Page for Windows Phone 8.1	// let's assume that you have a simple class:\npublic class PassedData\n{\n   public string Name { get; set; }\n   public int Value { get; set; }\n}\n\n// then you navigate like this:\nFrame.Navigate(typeof(Page1), new PassedData { Name = "my name", Value = 10 });\n\n// and in target Page you retrive the information:\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    PassedData data = e.Parameter as PassedData;\n}	0
8095232	8095115	Invalid anonymous type member declerator when joining a field with a static value	join t7 in db.Notes.DefaultIfEmpty() on t2.Lead_ID equals t7.Item_ID into notes\nwhere t7.Item_ID == 5	0
8259302	7997766	Dot Net Charting - Stack two series, leave the other as normal bar chart	ChartThree.SeriesCollection[3].Type = SeriesType.AreaLine;	0
12844406	12844387	find area of 2 coordinates	(p2.X - p1.X) * (p2.Y - p1.Y)	0
14762747	14762369	How do I get instance of Webbrowser inside currently active tab in WinForms	public Control GetWebBrowserControl()\n{\n    foreach (Control ctl in TabControl1.SelectedTab.Controls) {\n        if (ctl is WebBrowser) {\n            return ctl;\n        }\n    }\n    return null;\n}	0
32542466	32541780	Getting CPU usage of a specific Service in C#	PerformanceCounter counter = new PerformanceCounter("Process", "% Processor Time", "ACService", true);	0
7659429	7659379	Dependency Injection with Cyclic Dependency	[Dependency]	0
16631482	16628701	WPF GUI starving network messages	public delegate int PassH264Stream(byte[] buffer, int len);\npublic PASSH264Stream TestDelegate = {};\n\nTestDelegate += (buffer, len) => Application.Current.Dispatcher.BeginInvoke(new Action(()\n  => ReceiveInUiThread(buffer, len)), DispatcherPriority.Render);	0
5899505	5898094	Should I use a message queue to guarantee a windows service only operates on one record at time?	Queue<WorkItem>	0
22129184	22129126	Access all instances of class with foreach	public int getSumOfTimes()\n{\n     int sum;\n\n     if (subordinates.Count() == 0)\n     {\n       sum =  getIdealTime();\n     }\n     else\n     {\n       foreach (var prodel in subordinates)\n       {\n         sum += prodel.getSumOfTimes();\n       }\n     }\n     return sum;\n}	0
13504668	13504557	Change text of a listview	int threshold = 5;\n\nforeach (ListViewItem item in listView1.Items)\n{\n    if (item.SubItems.Count > threshold)\n    {\n        if (item.SubItems[5].Text.Contains("Yes"))\n        {\n            // Do your work here\n        }\n    }\n}	0
11447779	11447684	Save excel file in a temporary folder in c#	if (openFileDialog1.ShowDialog() == DialogResult.OK) \n{ \n    File.Copy(openFileDialog1.FileName, Path.Combine(Path.GetTempPath(), Path.GetFileName(openFileDialog1.FileName)), true); \n}	0
8916362	8916155	ASP.NET Download Image file from URL with querystring	string remoteImgPath = "https://mysource.com/2012-08-01/Images/front/y/123456789.jpg?api_key=RgTYUSXe7783u45sRR";\nUri remoteImgPathUri = new Uri(remoteImgPath);\nstring remoteImgPathWithoutQuery = remoteImgPathUri.GetLeftPart(UriPartial.Path);\nstring fileName = Path.GetFileName(remoteImgPathWithoutQuery);\nstring localPath = AppDomain.CurrentDomain.BaseDirectory + "LocalFolder\\Images\\Originals\\" + fileName;\nWebClient webClient = new WebClient();\nwebClient.DownloadFile(remoteImgPath, localPath);\nreturn localPath;	0
6386633	6386602	how to conver date string from one format to another format in c#?	DateTime.Parse(myDate).ToString("yyyy-MM-dd");	0
23499303	23498426	Base 64 Encoding XML to post to webservice	string byteArrayEncoded = System.Convert.ToBase64String(plainTextBytes, 0, plainTextBytes.Length);\nstring byteArrayUrlEncoded = System.Web.HttpUtility.UrlEncode(byteArrayEncoded);\nbyte[] byteArray = Encoding.UTF8.GetBytes("xmlpost=" + byteArrayUrlEncoded + "&test=1");	0
10035740	10035595	C# WinForms need to automatically align a set of labels inside a control in a simple topleft fashion	//Sample:\n//Assuming you are creating your labels from \n//List<string>\n\n\n\n List<string> labels=new List<string>();\n    labels.Add("If");\n    labels.Add("variable");\n    labels.Add("=");\n    labels.Add("5");\n    for (int i = 0; i < labels.Count; i++)\n    {\n        Label lbl = new Label();\n        lbl.Text = labels[i];\n        flowLayoutPanel1.Controls.Add(lbl);\n    }	0
9925873	9925742	TryGetValue with splitwords	var repStr = txtBox.Text;\n\nforeach (var kvp in d)\n{\n    repStr = repStr.Replace(kvp.Key, kvp.Value);\n}\n\ntxtBox2.Text = repStr;	0
29484542	29483660	How to transpose matrix?	public double[,] Transpose(double[,] matrix)\n{\n    int w = matrix.GetLength(0);\n    int h = matrix.GetLength(1);\n\n    double[,] result = new double[h, w];\n\n    for (int i = 0; i < w; i++)\n    {\n        for (int j = 0; j < h; j++)\n        {\n            result[j, i] = matrix[i, j];\n        }\n    }\n\n    return result;\n}	0
3547264	3523477	How to stop a bindingSouce/ComboBox from changing selection	bool ignoreEvent = false;\nobject lastSelectedItem = null;\n\nvoid comboBox1_SelectedIndexChanged(object sender, EventArgs e) {\n    if (ignoreEvent) return;\n\n    if (CheckForChanges()) {\n        if (MessageBox.Show("Do you want to save changes?", "Save changes", MessageBoxButtons.YesNo) == DialogResult.Yes) {\n            ignoreEvent = true;\n            comboBox1.SelectedItem = lastSelectedItem;\n            ignoreEvent = false;\n        }\n        else {\n            // call CancelEdit() here\n        }          \n    }\n\n    lastSelectedItem = comboBox1.SelectedItem;\n}	0
4250990	4250787	Override the Listbox Control to return a concatenated string value	public static string GetSelectedItems(this ListBox lbox)\n    {\n        List<string> selectedValues = new List<string>();\n\n        int[] selectedIndeces = lbox.GetSelectedIndices();\n\n        foreach (int i in selectedIndeces)\n            selectedValues.Add(lbox.Items[i].Value);\n\n        return String.Join(",",selectedValues.ToArray());\n    }\n\n    public static void SetSelectedItems(this ListBox lbox, string[] values)\n    {\n        foreach (string value in values)\n        {\n            lbox.Items[lbox.Items.IndexOf(lbox.Items.FindByValue(value))].Selected = true;\n        }\n    }\n\n    public static void AddListItems(this ListBox lbox, string[] values)\n    {\n        foreach (string value in values)\n        {\n            ListItem item = new ListItem(value);\n            lbox.Items.Add(item);\n        }\n    }	0
23456610	23456143	Using FileOpenPicker with Silverlight	Microsoft.Phone.Shell.PhoneApplicationService.Current.ContractActivated +=  Application_ContractActivated;\n\nprivate void Application_ContractActivated(object sender, IActivatedEventArgs e)\n{\n        var filePickerContinuationArgs = e as FileOpenPickerContinuationEventArgs;\n        if (filePickerContinuationArgs != null)\n        {\n        // Handle file here\n        }\n}	0
31863105	31862798	Validating Annotated ViewModel at a non Asp.Net MVC nor Web API	using System.Collections;\nusing System.Collections.Generic;\nusing System.ComponentModel.DataAnnotations;\n\npublic class DataAnnotationsValidator\n{\n    public bool TryValidate(object @object, out ICollection<ValidationResult> results)\n    {\n        var context = new ValidationContext(@object, serviceProvider: null, items: null);\n        results = new List<ValidationResult>();\n\n        return Validator.TryValidateObject(\n            @object,\n            context,\n            results,\n            validateAllProperties: true\n        );\n    }\n}	0
15315796	15315279	Lingering WPF Drop Shadow	TilesControl.Items.Refresh();	0
19429641	19429506	Trouble in fetching results from server in windows phone	we.Message	0
20716641	20716623	simple cast from interface method result to integer	public object Convert(object value)\n{ \n   int c;\n   if(value is IBookRepository)\n   {\n      c = (int)((IBookRepository)value).CountAllBooks();\n   }\n   return c;\n}	0
28276521	28218160	How do I transfer this SQL statement into a LINQ query?	Date = grp.Where(g => g.CRTI == grp.Max(s => s.CRTI) && g.STATUS == 9).Max(s => s.CRTI)	0
30966619	30966506	C# Static arrays - asigning values of static array to other static array	a2 = a1.Clone() as double[];	0
3927407	3927272	C# + OLEDB insert varchar with special character?	OleDbCommand cmd = new OleDbCommand ( "INSERT INTO dirs-arcs (nombre, formato, tamano, path, tags) VALUES (@name, @format, @tamano, @path, @tags)", connection);\n\ncmd.Parameters.Add( "@name", OleDbType.VarChar ).Value = name;\n// add all parameters	0
33430616	33430343	Resample 2D Array from 2x2 to 4x4	for (int k = 0; k < 4; k++)\n        {\n            for (int l = 0; l < 4; l++)\n            {\n                newdata[k][l] = data[k/2][l/2];\n            }\n        }	0
3042615	3042561	Open cl.exe from C# application	string filePath = "c:\program files\xyz\cl.exe";\nSystem.Diagnostics.Process.Start(filePath);	0
7700005	7699914	print the items of an array list in a textfile	public Form1()\n{\n    InitializeComponent();\n\n    private TextBox[] TextBoxes = {textBox1, textBox2, textBox3, textBox4, textBox5, textBox6};\n\n    private List<string> storeItems = new List<string>();\n}\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    var buffer = new StringBuilder();\n    foreach(var textBox in textBoxes)\n    {\n        if (string.IsNullOrEmpty(textBox.Text))\n        {\n            textBox.BackColor = Color.FromName("LightSalmon");\n            MessageBox.Show("This item cannot be left blank");\n            textBox.Focus();\n            return;\n        }\n        textBox.BackColor = Colors.FromName("Window");\n        buffer.Append(textBox.Text);\n    }\n\n    var result = buffer.ToString();\n    storeItems.Add(result);\n    System.IO.File.AppendAllText(@"C:\Users\v\Desktop\text.txt", Environment.NewLine + result);\n}	0
23332389	23286728	Using same bind variable multiple times	c.BindByName = true;	0
29327343	29327235	How to simulate ModelState.IsValid in C# winform application for any model validation	var validationContext = new ValidationContext(movie, null, null);\nvar results = new List<ValidationResult>();\n\n\nif (Validator.TryValidateObject(movie, validationContext, results, true))\n{\n    db.Movies.Add(movie);\n    db.SaveChanges();\n    //Instead of a Redirect here, you need to do something WinForms to display the main form or something like a Dialog Close.\n    //return RedirectToAction("Index");\n} else {\n   //Display validation errors\n   //These are available in your results.       \n}	0
12834578	12828739	Entity Framework set navigation property to null	LedProject project = db.LedProject\n    .Include("ResponsibleUser")\n    .Where(p => p.ProjectId == projectId)\n    .FirstOrDefault();	0
27290144	27289454	download all images from webpage using c#	private void GetWebpage(string url)\n{\n    WebBrowser browser = new WebBrowser();\n    browser.Navigate(url);\n    browser.DocumentCompleted += new WebBrowserDocumentCompletedEventHandler(browser_DocumentCompleted);\n\n}\n\nvoid browser_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)\n{\n    var browser = (WebBrowser)sender;\n    var client = new WebClient();\n    foreach (var img in browser.Document.Images)\n    {\n        var image = img as HtmlElement;\n        var src = image.GetAttribute("src").TrimEnd('/');\n        if (!Uri.IsWellFormedUriString(src, UriKind.Absolute))\n        {\n            src = string.Concat(browser.Document.Url.AbsoluteUri, "/", src);\n        }\n\n        //Append any path to filename as needed\n        var filename = new string(src.Skip(src.LastIndexOf('/')+1).ToArray());\n        File.WriteAllBytes(filename, client.DownloadData(src));\n    }\n}	0
32031158	32031092	if char array split count is less than 2	string variable = txt.Text;\n        string[] strArr = variable.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);\n        if (strArr.Length < 2)\n        {\n\n        }	0
13917951	13917920	insert using LinqToSql	// Create a new Order object.\nOrder ord = new Order\n{\n    OrderID = 12000,\n    ShipCity = "Seattle",\n    OrderDate = DateTime.Now\n    // ???\n};\n\n// Add the new object to the Orders collection.\ndb.Orders.InsertOnSubmit(ord);\n\n// Submit the change to the database.\ntry\n{\n    db.SubmitChanges();\n}\ncatch (Exception e)\n{\n    Console.WriteLine(e);\n    // Make some adjustments.\n    // ...\n    // Try again.\n    db.SubmitChanges();\n}	0
24389232	24322026	Customize Bearer token JSON result in ASP.NET WebApi 2	public override async Task TokenEndpoint(OAuthTokenEndpointContext context)\n{\n    context.AdditionalResponseParameters.Add("username", "user@mail.com");\n\n    return Task.FromResult<object>(null);\n}	0
1824298	1823884	Generate Image with Microsoft .NET Chart Controls Library without Control	using System.Windows.Forms.DataVisualization.Charting;\nusing System.IO;\n...\n    public void GeneratePlot(IList<DataPoint> series, Stream outputStream) {\n      using (var ch = new Chart()) {\n        ch.ChartAreas.Add(new ChartArea());\n        var s = new Series();\n        foreach (var pnt in series) s.Points.Add(pnt);\n        ch.Series.Add(s);\n        ch.SaveImage(outputStream, ChartImageFormat.Jpeg);\n      }\n    }	0
10180034	10179016	Self Updating a POCO Model class from external webservice	System.Threading.Timer	0
23752846	23751566	internal interface implementation in a public interface	internal interface ICommand\n{\n    // some methods...\n}\n\npublic interface IProject\n{\n    // some other methods...\n}\n\ninternal interface IProjectWithCommands : IProject\n{\n    ICommand Command { get; set; }\n}	0
26865186	26864990	wait for completing operation in awesomium in C#	int Sec = 1000;  // 1 sec 1000ms\n    int i = 0 ;\n    do{\n       //do application events\n      Application.DoEvents();\n       //sleep for 1 mili second \n      System.Threading.Thread.Sleep(1);\n      i++;  //increase i by 1 milisecond\n\n    }while((Sec*5) > i );	0
2173885	2173870	How can i get Last xx item from XML file with Xpath() query in C#?	XPath="/newsSection/news[position()>last()-5]	0
709573	709562	How to remove selected items from ListBox when a DataSource is assigned to it in C#?	DataRowView rowView = listBox.SelectedItem as DataRowView;\n\nif (null == rowView)\n{\n    return;\n}\n\ndt.Rows.Remove(rowView.Row);	0
16151223	16150329	i want to parse my script file by regex in c#	public static IEnumerable<string> GetScriptSection(string file, string section)\n{\n    var startMatch = string.Format("[{0}]", section);\n    var endMatch = string.Format("[/{0}]", section);\n    var lines = file.Split(Environment.NewLine.ToCharArray(), StringSplitOptions.RemoveEmptyEntries).Select(s => s.Trim()).ToList();\n\n    int startIndex = lines.FindIndex(f => f == startMatch) + 1;\n    int endIndex = lines.FindLastIndex(f => f == endMatch);\n\n    if(endIndex == -1)\n    {\n        endIndex = lines.FindIndex(startIndex,  f => f.StartsWith("[") && lines.IndexOf(f) > startIndex);\n        endIndex = endIndex == -1 ? lines.Count : endIndex;\n    }\n\n    return lines.GetRange(startIndex, endIndex - startIndex).Where(l => !string.IsNullOrWhiteSpace(l)).ToList();\n}	0
17792821	17792275	Reversed for loop	int number = int.Parse(textBox1.Text);\nfor (int row = 0; row < number; row++)\n{\n    for (int x = number - row; x > 0; x--)\n    {\n        textBox2.Text = textBox2.Text + "X";\n    }\n    textBox2.Text = textBox2.Text + Environment.NewLine;\n}	0
20125266	20123741	Copy array to 2D array with length 1 for second dimension	Array.Resize	0
12546110	12546006	Create one only foreach loop for all controls in a GroupControl	foreach(object control in InformationsGroupControl.Controls)\n{\n    BaseEdit editableControl = control as BaseEdit;\n    if(editableControl != null)\n        editableControl.Properties.ReadOnly = false;\n}	0
13581101	13580680	Find list of item properties	employees\n.Where(emp => emp.Designation.Equals("Executive"))\n.Select(item => item.EmpNo).ToList()	0
1813592	1813577	Getting information from button1_click() to button2_click()	class MyForm : Form\n{\n    MyType data1;\n    MyType data2;\n\n\n    private void button1_click(object sender, EventArgs e)\n    {\n         //generate data1, data2, data3, data4.. <-- here you just set the state of the Form\n    }\n\n\n\n    private void button2_click(object sender, EventArgs e)\n    {\n        //do processing using data1, data2, data3, data4.. <-- here you use the state set by button 1\n    }\n}	0
5419546	5419399	writing to xml attributes	XmlAttribute value = xmlDoc.CreateAttribute("value");\nchildNode1.attributes.appendChild(value);	0
19005980	19005850	Shared application resources in MEF	[ImportingConstructor]	0
30936423	30936063	Need to break the line at some index and without breaking the word using c#	string innerString = "Clicking Log Out will clear our cookies and log you out of Stack Overflow on all devices";\nif (innerString.Length > 37)\n{\n    int startvalue = 38;\n    while (startvalue < innerString.Length)\n    {\n        if (innerString[startvalue] == ' ')\n        {\n            innerString = innerString.Insert(startvalue, System.Environment.NewLine).TrimEnd();\n            startvalue = startvalue + 38;\n        }\n        else\n        {\n            int i = innerString.LastIndexOf(" ", startvalue);\n            startvalue = i++;\n            innerString = innerString.Insert(startvalue, System.Environment.NewLine).TrimEnd();\n            startvalue = startvalue + 38;\n        }\n    }\n}	0
7863007	7862686	DataSet Insert into tables	public static string BuildSqlNativeConnStr(string server, string database)\n{\n  return string.Format("Data Source={0};Initial Catalog={1};Integrated Security=True;", server, database);\n}\nprivate void simpleButton1_Click(object sender, EventArgs e)\n{\n  const string query = "Insert Into Employees (RepNumber, HireDate) Values (@RepNumber, @HireDate)";\n  string connStr = BuildSqlNativeConnStr("apex2006sql", "Leather");\n\n  try\n  {\n    using (SqlConnection conn = new SqlConnection(connStr))\n    {\n      conn.Open();\n      using (SqlCommand cmd = new SqlCommand(query, conn))\n      {\n        cmd.Parameters.Add(new SqlParameter("@RepNumber", 50));\n        cmd.Parameters.Add(new SqlParameter("@HireDate", DateTime.Today));\n        cmd.ExecuteNonQuery();\n      }\n    }\n  }\n  catch (SqlException)\n  {\n    System.Diagnostics.Debugger.Break();\n  }\n}	0
28223187	28221449	Nested Loop function taking minuets to run, anyway to improve efficiency?	Enumerable.Range(char.MinValue, char.MaxValue - char.MinValue)	0
28650816	28650726	Add Values to a String in C# only if they're not null	string[] addressParts = \n   { location.Street1, location.Street2, location.City, location.PostalCode};\n\nstring inputAddress = string.Join(" ", addressParts.Where(s=> !string.IsNullOrEmpty(s)));\ninputAddress = HttpUtility.UrlEncode(inputAddress);	0
32168491	32168414	runtime Movable rectangle windows store app	private void Rectangle_Click(object sender, RoutedEventArgs e)\n{\n    var rec = new Rectangle();\n    rec.Height = 100;\n    rec.Width = 100;\n    rec.Fill = new SolidColorBrush(Colors.Violet);\n\n    rec.ManipulationMode=ManipulationModes.All;\n    rec.ManipulationDelta += rec_ManipulationDelta;\n    rec.RenderTransform=new TranslateTransform(); // Create new TranslateTransform and assign to the rectangle\n    board.Children.Add(rec);\n\n}\n\nvoid rec_ManipulationDelta(object sender, ManipulationDeltaRoutedEventArgs e)\n{\n    Rectangle recSender = (Rectangle) sender; // Get the Rectangle\n    TranslateTransform ttSender = recSender.RenderTransform as TranslateTransform; // Get the Rectangle's RenderTransform (which is a TranslateTransform)\n\n    ttSender.X += e.Delta.Translation.X;\n    ttSender.Y += e.Delta.Translation.Y;\n\n}	0
15147166	15145209	How to play a WPF Sound File resource	new Uri(@"pack://application:,,,/Resources/logo.png")	0
2173611	2173414	C# byte[] comparison without bound checks	using System;\nusing System.Runtime.InteropServices;\nusing System.Diagnostics;\n\nclass Program {\n  static void Main(string[] args) {\n    byte[] arr1 = new byte[50 * 1024 * 1024];\n    byte[] arr2 = new byte[50 * 1024 * 1024];\n    var sw = Stopwatch.StartNew();\n    bool equal = memcmp(arr1, arr2, arr1.Length) == 0;\n    sw.Stop();\n    Console.WriteLine(sw.ElapsedMilliseconds);\n    Console.ReadLine();\n  }\n  [DllImport("msvcrt.dll")]\n  private static extern int memcmp(byte[] arr1, byte[] arr2, int cnt);\n}	0
7359027	7358986	Convert Timer Interval in seconds and minutes	var timeSpan = TimeSpan.FromMilliseconds(5000);\n\nvar seconds = timeSpan.TotalSeconds;\nvar minutes = timeSpan.TotalMinutes;	0
6974362	6973960	Linq to entities get first or last from 2million rows	using (DataFeedEntities db = new DataFeedEntities())\n{\n    IntradayFuturesTick tick = db.IntradayFuturesTicks\n       .OrderByDescending(x => x.Id)\n       .Take(1)\n       .Single();\n}	0
28463704	28463577	Adding records to a CollectionViewSource resource, not showing up in a bound ListView	myCacheSrc = (CollectionViewSource)FindResource("myCacheSrc");\n        myCacheSrc.Source = new ObservableCollection<MyEFPOCO>();	0
24524119	24524061	Inconsistent DateTime.Parse behavour behaviour	CultureInfo.CurrentCulture.Calendar.TwoDigitYearMax	0
5521274	5521202	LINQ Contains Syntax with List<string>	var itemsAlreadyAdded = new int[] { 2, 4, 6 };\nvar newIds = new string[] { "2", "3" };\n\nvar itemsToAdd = newIds.Except(itemsAlreadyAdded.Select(iaa => iaa.ToString()));\n\nforeach (var item in itemsToAdd)\n{\n    Console.WriteLine(item);\n}\n\nConsole.ReadLine();	0
7035875	7025590	clear all radio buttons in a page	private void button1_Click(object sender, EventArgs e) {\n\n    var cntls = GetAll(this, typeof(RadioButton));\n                    foreach (Control cntrl in cntls)\n                    {\n                        RadioButton _rb = (RadioButton)cntrl;\n                        if (_rb.Checked)\n                        {\n                            _rb.Checked = false;\n\n                        }\n                    }\n\n    }\n\n    public IEnumerable<Control> GetAll(Control control, Type type)\n            {\n                var controls = control.Controls.Cast<Control>();\n                return controls.SelectMany(ctrls => GetAll(ctrls, type)).Concat(controls).Where(c => c.GetType() == type);\n            }	0
3995119	3994601	Globally changing format of negative currency numbers in C#	System.Globalization.CultureInfo modCulture = new System.Globalization.CultureInfo("en-US");\n        modCulture.NumberFormat.CurrencyNegativePattern = 1;\n        Thread.CurrentThread.CurrentCulture = modCulture;	0
32987893	32987455	SQL Server Group by using LINQ	var result = from t in conn.TICKETS\n             join dept in conn.DEPARTMENT on t.FK_DEPT_ID equals dept.PK_DEPT_ID\n             select new { DeptName = dept.NAME, Status = t.STATUS }\n             into temp\n             group temp by new { temp.DeptName, temp.Status }\n             into g\n             select new { g.Key.DeptName, g.Key.Status, Count = g.Count()};	0
7290456	7289891	How to load data from XML to List	XDocument xdoc = XDocument.Load(url); // assuming you're pulling your xml from a service. \n\nif (xdoc != null)\n{\n    var levels =\n        (from l in xdoc.Descendants("Level")\n            select new Level\n            {\n                levelNumber = l.Attribute("levelNumber").Value,\n                startingX = l.Attribute("startingX").Value,\n                startingY = l.Attribute("startingy").Value,\n                cellsList = (from c in l.Descendants("Cell")\n                            select new Cell\n                            {\n                                CellType = c.Attribute("CellType").Value,\n                                PositionX = c.Attribute("PostionX").Value,\n                                PositionY = c.Attribute("PositionY").Value\n                            }).ToList()\n            }\n        ).ToList();\n}	0
2778366	2773936	Grouping in datagrid - rows not getting displayed	AutoGenerateColumns="True"	0
9852738	9852454	Get data from SQL Server database into label	string MyPageTitle="MyPageTitle"; // your page title here\nstring myConnectionString = "connectionstring"; //you connectionstring goes here\n\nSqlCommand cmd= new SqlCommand("select Price from Tickets where ConcertName ='" + MyPageTitle.Replace("'","''") + "'" , new SqlConnection(myConnectionString));\ncmd.Connection.Open();\nlabelPrice.Text= cmd.ExecuteScalar().ToString(); // assign to your label\ncmd.Connection.Close();	0
23291122	23290347	How to get a list which contains at least all the values of another list?	var query = from doc in query\n            let tagIds = from t in doc.Tags select t.Id\n            where parameters.All(p => tagIds.Contains(p))\n            select doc;	0
32142120	32141980	Counting number of element in xml file	XDocument doc = XDocument.Load(@"W:\Prajwal\FMU_EXTRACT\modelDescription.xml");\nint ScalarVariableCount = doc.Root.Element("ModelVariables")\n                                  .Elements("ScalarVariable").Count();	0
6496929	6496881	How to determine duplicates in a collection of ints?	var dups = collection.GroupBy(x => x)\n                     .Where(g => g.Count() > 1)\n                     .Select(g => g.Key);	0
28862629	28862541	Add list items to datagridview and database table	foreach (var currentItem in RoleName.SelectedItems)\n            {\n                cmdAdd.Parameters["@UserID"].Value = label1.Text;\n                cmdAdd.Parameters["@RoleName"].Value = currentItem // Or i in your code. \n//RoleName.SelectedItem; selected item is always same.\n                cmdAdd.ExecuteNonQuery();\n            }	0
1933887	1933855	How can i retrieve a table from stored procedure to a datatable	string connString = "<your connection string>";\nstring sql = "name of your sp";\n\nusing(SqlConnection conn = new SqlConnection(connString)) \n{\n    try \n    {\n        using(SqlDataAdapter da = new SqlDataAdapter()) \n        {\n            da.SelectCommand = new SqlCommand(sql, conn);\n            da.SelectCommand.CommandType = CommandType.StoredProcedure;\n\n            DataSet ds = new DataSet();   \n            da.Fill(ds, "result_name");\n\n            DataTable dt = ds.Tables["result_name"];\n\n            foreach (DataRow row in dt.Rows) {\n                //manipulate your data\n            }\n        }    \n    } \n    catch(SQLException ex) \n    {\n        Console.WriteLine("SQL Error: " + ex.Message);\n    }\n    catch(Exception e) \n    {\n        Console.WriteLine("Error: " + e.Message);\n    }\n}	0
24436662	24436212	c# Custom control click event	protected override void OnMouseClick(MouseEventArgs e)\n{\n    int x = e.X;\n    int y = e.Y;\n\n    //Do your calculation here.\n}	0
22834378	22833938	Replace words in string2 with string1 in C#	string s1 = "This city is very beautiful";\n        string s2 = "The citi is very beautyful - and its also very big:";\n\n        if (!string.IsNullOrEmpty(s2) && s2.Contains(' '))\n        {\n            string[] partsS1 = s1.Split(' ');\n            string[] partsS2 = s2.Split(' ');\n            int count = partsS1.Length;\n            for (int a = 0; a < count; a++)\n            {\n                if (partsS2.Length > count)\n                {\n                    if (partsS1[a] != partsS2[a])\n                    {\n                        partsS2[a] = partsS1[a];\n                    }\n                }\n            }\n            string final = string.Empty;\n            foreach (string s in partsS2)\n            {\n                final += s + " ";\n            }\n            final = final.TrimEnd(' ');\n            Console.WriteLine(final);\n        }	0
8882590	8882435	Accepted collection for working with Excel data	// Presumes a DataTable named "Orders" that has a column named "Total."\nDataTable table;\ntable = dataSet.Tables["Orders"];\n\n// Declare an object variable.\nobject sumObject;\nsumObject = table.Compute("Sum(Total)", "EmpID = 5");	0
14892577	14892461	File "Open with" my Windows Store App	protected override void OnFileActivated(FileActivatedEventArgs args)\n{\n       // TODO: Handle file activation\n\n       // The number of files received is args.Files.Size\n       // The first file is args.Files[0].Name\n}	0
29598800	29598652	Construct expression for where through lambdas	IQueryable<Student> q = dbContext.Students.AsQueryable();\n\nif (crit.name != null)\n    q = q.Where(c => c.name == crit.name);\n\nif (crit.age != null)\n    q = q.Where(c => c.age== crit.age);	0
16012590	16012543	Generate a unique integer based on given string	myString.GetHashCode()	0
18426511	18426495	copy a character with specific length	string text = new string('y', 4);	0
14233728	13310426	XAML: Get relative path to file at design time	var path = "SampleData/stub.xml";\nvar res = Application.GetResourceStream(new Uri(path, UriKind.Relative))\nxml = new StreamReader(res.Stream).ReadToEnd();	0
7807911	7807837	Is there a way to print the date that an application was last published?	System.IO.File.GetLastWriteTime(Assembly.GetExecutingAssembly().Location)	0
22733226	22733133	Block FileDialog from displaying unwanted extensions	FileDialog fd = new OpenFileDialog();\nfd.Filter = "*.txt|*.txt";\nfd.ShowDialog();\n\nif (Path.GetExtension(fd.FileName).ToLower() != ".txt")\n    MessageBox.Show("Choose a text file!");	0
6105857	6104366	XNA Vector3 into Vector3D	public static Vector3D ToVector3D(Vector3 input)\n{\n   return new Vector3D( (float)input.X, (float)input.Y, (float)input.Z );\n}	0
14498304	14498245	How to send Hashtable through TCP?	BinaryFormatter binaryFormatter = new BinaryFormatter();\nbinaryFormatter.Serialize(streamWriter.BaseStream, Users);	0
16725847	12345077	Index out of range for rectangle array?	snakeBodyRectangleArray[bodyNumber] = new Rectangle((int)snakeBodyArray[bodyNumber].X, (int)snakeBodyArray[bodyNumber].Y, textureSnakeBody.Width, textureSnakeBody.Height);	0
17211538	17210936	c# acces array outside for loop	string[] linesSplitted = new string[5];\nfor (int i = 0; i < 5; i++)\n{\n    linesSplitted[i] = lines[i].Split(':')[1];\n}	0
1216990	1215054	Design by Contract: Can you have an Interface with a Protocol?	void IPlugin.Reset()\n    {\n        this.number = null;\n        this.state = State.NotReady;\n        Contract.Assume(((IPlugin)this).State == this.state);\n    }	0
5273909	5273861	MIN and MAX for a year from datetime using linq to sql	var minYear = dbContext.News.Min(x => x.ArticleDate.Year);\nvar maxYear = dbContext.News.Max(x => x.ArticleDate.Year);	0
22175755	22174335	Mapping Property to different table Fluent NHibernate	mapping.Join( "Table1Notes", map =>\n{\n    map.KeyColumn( "Table1Id" );\n    map.Map( x => x.Notes ).Nullable().LazyLoad();\n    map.Optional();\n} );	0
15136162	15136134	C# how to use enum with switch	switch(op)\n{\n     case Operator.PLUS:\n     {\n\n     }\n}	0
21570478	21570309	adding items into list by for loops	List<City> cities = new List<City> ();\n\nforeach (RouteServiceRef.Hawker rp in recommendPlaceList)\n    {\n        hawkername = rp.hawkername;\n        address = rp.address;\n        postal = rp.postal;\n        coordX = rp.xcoord;\n        coordY = rp.ycoord;\n        popularity = rp.popularity;\n        cities.Add(new City(){Name = hawkername, Population = popularity });\n    }	0
31277578	31277199	Unity3D casting ray from the middle of the screen	Vector3 rayOrigin = new Vector3(0.5f, 0.5f, 0f); // center of the screen\nfloat rayLength = 500f;\n\n// actual Ray\nRay ray = Camera.main.ViewportPointToRay(rayOrigin);\n\n// debug Ray\nDebug.DrawRay(ray.origin, ray.direction * rayLength, Color.red);\n\nRaycastHit hit;\nif (Physics.Raycast(ray, out hit, rayLength))\n{\n    // our Ray intersected a collider\n}	0
4397834	4397740	Parse XML using LINQ and fill existing object's properties rather than creating a new one	var dropThis =\n  (from tutorial in xmlDoc.Descendants("Tutorial")\n   select new\n   {\n     Author = (myTutorial.Author = (string)tutorial.Element("Author")),\n     Title = (myTutorial.Title = (string)tutorial.Element("Title")),\n     Date = (myTutorial.Date = (DateTime)tutorial.Element("Date")),\n   }).First();	0
11893902	11788932	How to check if a Part of a Foreign Window is overlayed	public class WinAPI {\n    [DllImport("user32.dll")]\n    public static extern IntPtr SetWindowLong(IntPtr hWnd, int nIndex, uint dwNewLong);\n\n    public const int GWL_HWNDPARENT = -8;\n}\n\n\nWinAPI.SetWindowLong(this.Handle, WinAPI.GWL_HWNDPARENT, (uint)this.ObservedHandle);	0
14615136	14614814	Pass constructor with Ninject	Bind<IMarketRepository>().To<MarketRepository>().WithConstructorArgument("sessionId", "Session ID here");	0
22636222	22636135	How do I get detailed file information if I only have the file name?	foreach (FileInfo fil in files)\n{\n    listView2.Items.Add(\n        new ListViewItem(\n            new string[] {\n                fil.Name,\n                fil.LastWriteTime.ToString(),\n                fil.Length.ToString()\n            }\n        )\n    );\n}	0
28000546	27975750	Cannot load from assembly via nunit-console but works in Xamarin Studio	/Library/Frameworks/Mono.framework/Commands/nunit-console4 /my/test/project/Test.dll	0
1970797	1970791	How to implement Runtime for movies in C#?	System.TimeSpan	0
6218369	6158002	validate xml string content including encoding using C#	try\n        {\n            byte[] xmlContentInBytes = new System.Text.UnicodeEncoding().GetBytes(xmlContent);\n\n            System.Text.UTF8Encoding utf8 = new System.Text.UTF8Encoding(false, true);\n            utf8.GetChars(xmlContentInBytes);\n        }\n        catch (Exception ex)\n        {\n            Console.WriteLine(ex.Message);\n            return false;\n        }	0
17960633	17958208	How do i use a progressBar to perform an progress for each process in my program?	// Form method for updating progress bar; callable from worker thread\npublic void UpdateProgressBar(double progress)\n{\n    // dispatch the update onto the form's thread\n    Dispatcher.BeginInvoke((Action<double>)((n) =>\n    {\n        // do the update in the form's thread\n        progressBar1.Value = n;\n    }), progress);\n}	0
4062368	4025308	How do you have a bulletted list in migradoc / pdfsharp	// Add some text to the paragraph\nparagraph.AddFormattedText("Hello, World!", TextFormat.Italic);\n\n// Add Bulletlist begin\nStyle style = document.AddStyle("MyBulletList", "Normal");\nstyle.ParagraphFormat.LeftIndent = "0.5cm";\nstring[] items = "Dodge|Nissan|Ford|Chevy".Split('|');\nfor (int idx = 0; idx < items.Length; ++idx)\n{\n  ListInfo listinfo = new ListInfo();\n  listinfo.ContinuePreviousList = idx > 0;\n  listinfo.ListType = ListType.BulletList1;\n  paragraph = section.AddParagraph(items[idx]);\n  paragraph.Style = "MyBulletList";\n  paragraph.Format.ListInfo = listinfo;\n}\n// Add Bulletlist end\n\nreturn document;	0
4429167	4429117	WPF: Dynamical Label addition in Grid	private void AddLabelDynamically()\n    {\n        this.LabelGrid.ColumnDefinitions.Clear();\n        this.LabelGrid.RowDefinitions.Clear();\n\n        this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition());\n        this.LabelGrid.ColumnDefinitions.Add(new ColumnDefinition());\n\n        for (int i = 0; i < 3; i++)\n        {\n            this.LabelGrid.RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });\n\n            Label nameLabel = new Label(); nameLabel.Content = "KEY :" + i.ToString();\n            Label dataLabel = new Label(); dataLabel.Content = "VALUE :" + i.ToString();\n\n            Grid.SetRow(nameLabel, i);\n            Grid.SetRow(dataLabel, i);\n\n            Grid.SetColumn(nameLabel, 0);\n            Grid.SetColumn(dataLabel, 1);\n\n            //I want to creatre the Seperate coloum and row to  display KEY\n            // VALUE Pair distinctly\n            this.LabelGrid.Children.Add(nameLabel);\n            this.LabelGrid.Children.Add(dataLabel);\n        }\n    }	0
12061805	12061667	Format decimal to string	public string SpecialFormatDecimal(decimal input)\n{\n    return (input / 100000000).ToString("#,##0.00000000", System.Globalization.CultureInfo.GetCultureInfo("en-US"));\n}	0
31334580	31333473	Comparing two DataTables to determine if it is modified	DataTable original;\nDataTable modified;\n\n// your stuff\n\nmodified = modified.AsEnumerable().Zip<DataRow, DataRow, DataRow>(original.AsEnumerable(), (DataRow modif, DataRow orig) =>\n{\n    if (!orig.ItemArray.SequenceEqual<object>(modif.ItemArray))\n    {\n        modif.SetModified();\n    }\n    return modif;\n}).CopyToDataTable<DataRow>();	0
6174729	6174536	Help with GDI+ image drawing	public static void Main()\n{\n\n    AnimEngine f1 = new AnimEngine();\n    f1.Paint += new PaintEventHandler(f1.draw);\n    Application.Run(f1);\n    f1.Refresh();\n    return;\n}	0
5828511	5828455	How to access the folders available in the server using IP address	\\10.10.27.35\folder\subfolder\	0
18005376	18005214	Convert a NameValueCollection to a dynamic object	IDictionary<string, string> dict = new Dictionary<string, string> { { "Foo", "Bar" } };\ndynamic dobj = dict.ToExpando();\ndobj.Foo = "Baz";	0
8903951	8903878	alert response from server via jquery	error: function(header, status, exception) {\n    alert(exception.Message);\n}	0
299878	299869	What could be used as a double sided Resource Dictionary?	public class DoubleLookup<TKey, TValue>\n{\n  private IDictionary<TKey, TValue> keys;\n  private IDictionary<TValue, TKey> values;\n\n  //stuff...\n\n  public void Add(TKey key, TValue value)\n  {\n    this.keys.Add(key, value);\n    this.values.Add(value, key);\n  }\n\n  public TKey GetKeyFromValue(TValue value)\n  {\n    return this.values[value];\n  }\n\n  public TValue GetValueFromKey(TKey key)\n  {\n    return this.keys[key];\n  }\n\n\n}	0
20674646	20215476	Trying to convert a calculator textbox items into int and char ( for + * and such ) or making them separated from start	String x;\nchar ch = x[i];\nif ( ch == '+' || ch =='-' || ch =='*' || ch == '/' || ch == '^' )\n{//Here comes the Operators, as for me it works for pushing operators into stack }\nelse\n{//Here comes the Operands, as for me , it works for putting them in another String }	0
170040	170028	How would you simplify Entering and Exiting a ReaderWriterLock?	using System;\nusing System.Threading;\n\nclass Program\n{\n    static void Main()\n    {\n        ReaderWriterLockSlim sync = new ReaderWriterLockSlim();\n\n        using (sync.Read())\n        {\n           // etc    \n        }\n    }\n\n\n}\npublic static class ReaderWriterExt\n{\n    sealed class ReadLockToken : IDisposable\n    {\n        private ReaderWriterLockSlim sync;\n        public ReadLockToken(ReaderWriterLockSlim sync)\n        {\n            this.sync = sync;\n            sync.EnterReadLock();\n        }\n        public void Dispose()\n        {\n            if (sync != null)\n            {\n                sync.ExitReadLock();\n                sync = null;\n            }\n        }\n    }\n    public static IDisposable Read(this ReaderWriterLockSlim obj)\n    {\n        return new ReadLockToken(obj);\n    }\n}	0
9284515	9279122	Set a field readonly with a plugin	Xrm.Page.getControl('yourfieldname').setDisabled(true);	0
7774944	7774327	C# Data Grid View	DataTable resultsList = new DataTable();\nresultsList.Columns.Add("Time", typeof(String));\n...\nresultsList.Rows.Add(stat);	0
4295085	4295066	Get Grid.Column property from sender	var row = Grid.GetRow((Button)sender);\nvar col = Grid.GetColumn((Button)sender);	0
27531977	27531939	How do you create a generically constrained property on an interface?	public interface IWidgetGetter<T> where T : IWidget\n{\n    IEnumerable<T> Widgets { get; }\n}	0
12396376	12396256	Concatenating data from multiple sources and inserting as one row into SQL Table	string commandText = @"Insert INTO MyTable (Column1, Column2, Column3)\n                          SELECT FirstName, LastName, @TBValue\n                          FROM OtherTable where id = @QSValue";\ncmd.CommandText = commandText;\ncmd.Parameters.Add("@TBValue", tb_MyBox.Text);\ncmd.Parameters.Add("@QSValue", Request.QueryString["id"]);	0
25332589	25332449	Read text from console C#	using System.Diagnostics;\n...\nProcessStartInfo startInfo = new ProcessStartInfo();\nstartInfo.UseShellExecute = false; //required to redirect standart input/output\n\n// redirects on your choice\nstartInfo.RedirectStandardOutput = true;\nstartInfo.RedirectStandardOutput = true;\nstartInfo.RedirectStandardError = true;\n\nstartInfo.FileName = ...app path to execute...;\nstartInfo.Arguments = ...argumetns if required...;\n\nProcess process = new Process();\nprocess.StartInfo = startInfo;\nprocess.Start();\n\nprocess.StandardInput.WriteLine(...write whatever you want...);	0
26207980	26202493	Decimal group seperator for the fractional part	string input = Math.PI.ToString();\n string decSeparator = System.Threading.Thread.CurrentThread\n                      .CurrentCulture.NumberFormat.NumberGroupSeparator;\n Regex RX = new Regex(@"([0-9]{3})");\n string result  = RX.Replace(input , @"$1" + decSeparator);	0
4302551	4302387	how to add the rows to the datatable while executereader reads the rows from the table?	using (SqlConnection connection =\n           new SqlConnection(connectionString))\n{\n    SqlCommand command =\n        new SqlCommand(queryString, connection);\n    connection.Open();\n\n    SqlDataReader reader = command.ExecuteReader();\n\n    // Call Read before accessing data.\n    while (reader.Read())\n    {\n       CustomersRow newCustomersRow = Customers.NewCustomersRow();\n\n       newCustomersRow.CustomerID = reader[0].ToString();\n       newCustomersRow.CompanyName = reader[1].ToString();\n       dt.Rows.Add(newCustomersRow);\n    }\n\n    // Call Close when done reading.\n    reader.Close();\n}	0
9521908	9521877	How to combine two separate IQueryable<string> collections into one?	Concat()	0
26906301	26905328	Show xml nodes in textblock	var doc=new XmlDocument();\ndoc.LoadXml(File.ReadAllText(filePath));\nvar rootElement=doc.DocumentElement;\n\nvar Hilfeartikel=rootElement.GetElementsByTagName("Hilfeartikel")[0].InnerText;\nforeach (XmlElement Element in Hilfeartikel.ChildNodes)\n{\nvar frage=Element.GetElementsByTagName(Frage)[0].InnerText;\n}	0
28435710	28435664	add a value to a checklistbox , if the value does not already exists	var loanItems = chkBoxAssetLoan.Items;\n        if ((cboLoanAssetName.SelectedItem != null)\n        {\n             if (!loanItems.Contains(cboLoanAssetName.SelectedItem))\n            {\n            loanItems.Add(cboLoanAssetName.SelectedItem.ToString(), true);\n            }\n        }	0
13548746	13548659	Using numeric updown to step through an array	public partial class Form1 : Form\n{\n    string[] values;\n    public Form1()\n    {\n        InitializeComponent();\n        values = setValueArray();\n        numericUpDown1.Maximum = values.Length - 1;\n        numericUpDown1.Minimum = 0;\n    }\n\n    private string[] setValueArray()\n    {\n     return new string[] { "100", "90", "80", "70", "60" };\n    }\n\n    private void numericUpDown1_ValueChanged(object sender, EventArgs e)\n    {\n        label1.Text = values[(int)((NumericUpDown)sender).Value];\n    }\n}	0
12017450	12017392	CMD COPY cant find file	process1.StartInfo.Arguments = "/k copy /b \""+fi.Name+ "\" test.txt"; \nprocess1.StartInfo.FileName = "cmd.exe";	0
16108996	16108933	Using await with an event implementing CancelEventArgs	public DataStates DataState { get; private set; }\n\npublic Task UpdateDataStateAsync()\n{\n   // ... Use await as necessary	0
18534501	18534458	How to add item to listBox from other thread?	this.Invoke((MethodInvoker)(() => OutputBox.Items.Add(engineOutput)));	0
14548914	14548766	SimpleInjector resolving all types implementing an interface without explicitly binding	container.ResolveUnregisteredType += (s, e) =>\n{\n    Type type = e.UnregisteredType;\n\n    if (typeof(ISetting).IsAssignableFrom(type))\n    {\n        // If you need raw performance, there is also\n        // an overload that takes in an Expression.\n        e.Register(() =>\n        {\n            // Do something useful here. Example:\n            return Activator.CreateInstance(type);\n        });\n    }\n};	0
4777051	4776704	Using a reference to the main Window from a static class - Good practice?	Application.Current.Dispatcher.Invoke(DispatcherPriority.Background, (Action)delegate()\n    {\n    });	0
22303016	22302796	Regex password validation combination	var regEx = new Regex(@"^(?=(.*\d))(?=.*[a-z])(?=.*[A-Z])(?!\d).{7,}\D$");	0
20130989	20130930	Regex matches, gives 1 result	(?<=\<tr.*?(even|odd).*?\>).*?(?=\<)	0
10441351	10441303	Getting the value of self via reflection	if (obj is string)\n  Console.WriteLine(obj);\nelse\n    ... use reflection	0
20021280	20020531	How to create two navigation properties to one model (EF6 Code First)	protected override void OnModelCreating(DbModelBuilder modelBuilder)\n    {\n        modelBuilder.Entity<Match>()\n                    .HasRequired<Team>(i => i.TeamHome)\n                    .WithMany(i => i.Matches)\n                    .WillCascadeOnDelete(false);\n\n        base.OnModelCreating(modelBuilder);\n    }	0
30707329	30706072	Connecting 2 tables to a third using C# EF6	public int? LongitudinalId { get; set; }\npublic int? ChassisLongitudinalId { get; set; }	0
28279941	28245636	Selecting and Focusing a Datagrid based on a variable	var selectedObj = dgGrid.Items.Cast<YourClass>().First(a=> a.ID = txtFilter.Text);\nif(selectedObj != null)\n    dgGrid.SelectedItem =  selectedObj;	0
23357869	23357743	Zipping file with DotNetZip	zip.AddFile(fileName).FileName = System.IO.Path.GetFileName(fileName);	0
33493467	33493345	Using foreach to iterate through Generic List and add Values into List<DTO>	List<DTO> DTO = new List<DTO>;\nforeach (IGroup ele in Details)\n{\n  DTO request = new DTO();\n  // here you can extract details properties.\n  request.ActiveDirectoryGroupName  = ele.DisplayName;\n  ...\n  ...\n  DTO.Add(request);\n}	0
27057671	27057643	Assign value to a list of another class	public partial class remSolicitudesEnt {\n\n    private List<Solicitud> solicitudesField;\n\n    public List<Solicitud> Solicitudes \n    {\n        get { return this.solicitudesField; }\n        set { this.solicitudesField = value; }\n    }\n}	0
911069	910863	Using transactions with subsonic	Using ts As New System.Transactions.TransactionScope()\n  Using sharedConnectionScope As New SubSonic.SharedDbConnectionScope()\n\n' Do your individual saves here\n\n' If all OK\n      ts.Complete()\n\n   End Using\nEnd Using	0
32527954	32527612	Crystal reports Hide Details section on first page, but showing report header and page footer	pagenumber = 1	0
29860475	29860229	Single enumeration with multiple filters	Func<int, bool> isEven = n => n % 2 == 0;\nFunc<int, bool> isFive = n => n == 5;\nint diff = numbers.Aggregate(0, (sum, next) => isEven(next) ? sum + 1 : isFive(next) ? sum - 1 : sum);	0
14766191	14766086	How to calculate age in years from dob in c#	DateTime dob = .....\nDateTime Today = DateTime.Now;\nTimeSpan ts = Today - dob;\nDateTime Age = DateTime.MinValue + ts;\n\n\n// note: MinValue is 1/1/1 so we have to subtract...\nint Years = Age.Year - 1;\nint Months = Age.Month - 1;\nint Days = Age.Day - 1;	0
32392789	32392536	serialize objects to transfer into the messagequeue instance	BinaryMessageFormatter formatter = new BinaryMessageFormatter();\n   System.Messaging.Message message = new System.Messaging.Message(YourObject, formatter);	0
18057189	18057083	iterate through an enum type initialized with a string name?	List<KeyValuePair<string, object>> GetEnumInfo(string name)\n{\n    var type = Type.GetType(name);\n    return Enum.GetValues(type)\n            .Cast<object>()\n            .Select(v => new KeyValuePair<string, object>(Enum.GetName(type, v), v))\n            .ToList();\n}	0
12505432	12503391	How to get Colormap from Tif file	System.Drawing.Image image = Image.FromFile(@"Q:\my_image.tif");\nSystem.Drawing.Imaging.ColorPalette palette = image.Palette;\n//...palette.Entries is simply an array of System.Drawing.Color, modify to suit\n\n//crucial step - palette was retrieved as a copy, so\n//it is necessary to store the copy back to the image\nimage.Palette = palette;	0
14367417	14367057	Image reading at WPF application deployment environment	Icon="Resources/form1.ico"	0
29586502	29362249	Automatically implementing an interface for wrapping an existing implementation	public class RestPerformanceInterceptor : IInterceptionBehavior\n{\n    public bool WillExecute { get { return true; } }\n\n    public IEnumerable<Type> GetRequiredInterfaces()\n    {\n        return new[] { typeof(IA) };\n    }\n\n    public IMethodReturn Invoke(IMethodInvocation input, GetNextInterceptionBehaviorDelegate getNext)\n    {\n        var behaviorDelegate = getNext();\n\n        StartInNewTask(behaviorDelegate.Invoke(input, getNext));\n\n        return new Mock<IMethodReturn>();\n    }\n}	0
5875602	5873128	How do I wait for the results to be updated in RavenDB after DELETE	Session.Query<Foo>().Customize(x=>x.WaitForNonStaleResults())	0
11847229	11847122	Find a row in DataGridView containing the closest matched DateTime object	public DataGridViewRow FindRow(DataGridView dgv, DateTime searchID)\n    {\n        DataGridViewRow row = dgv.Rows\n            .Cast<DataGridViewRow>()\n            .Where(r => ((DateTime)r.Cells["DateAdded"].Value <= searchID))\n            .Last();\n\n        return row;\n    }	0
813247	813119	How do you call "Document Format" programmatically from C#?	Command cmd = _applicationObject.Commands.Item("Edit.FormatDocument", -1);\nobject dummy = null;\n_applicationObject.Commands.Raise(cmd.Guid, cmd.ID, ref dummy, ref dummy);	0
20351730	20351050	Converting a Value to NULL on server side in c#	protected void CustomersGridView_RowDataBound(Object sender, GridViewRowEventArgs e)\n  {\n    if(e.Row.RowType == DataControlRowType.DataRow)\n    {\n      if (e.Row.Cells[1].Text == "01/01/1754 00:00:00")\n      {\n          e.Row.Cells[1].Text = "Null";\n      }\n    }\n  }	0
13717829	13703083	Prevent images in rich text box	private void InputExpressionRchTxt_KeyDown(object sender, KeyEventArgs e)\n{\n    bool ctrlV = e.Modifiers == Keys.Control && e.KeyCode == Keys.V;\n    bool shiftIns = e.Modifiers == Keys.Shift && e.KeyCode == Keys.Insert;\n    if (ctrlV || shiftIns)\n        if (Clipboard.ContainsImage())\n            e.Handled = true;\n}	0
12379434	12377745	Insertion Sort in C#	public void insertionsort() { \n    int inner, temp; \n\n    for (int outer = 1; outer <= upper; outer++) {  \n        displayElements();                          \n        Console.WriteLine(); \n\n        temp = arr[outer]; \n        inner = outer; \n        while (inner > 0 && arr[inner - 1] >= temp) {  \n            arr[inner] = arr[inner-1]; \n            inner -= 1;\n        } \n\n        arr[inner] = temp; \n    }	0
23496591	23487634	ASP.NET Data Annotations Regular Expression: Don't allow following characters in Name: \, /, :, *, ;,	[Required]\n[RegularExpression(@"^[^\\/:*;\.\)\(]+$", ErrorMessage = "The characters ':', '.' ';', '*', '/' and '\' are not allowed")]\npublic string Name { get; set; }	0
13138062	13137077	Dynamic Neighborhood Coordinates	private Point[] GetNeighbors(int count)\n{\n    int a, x, y, c = count / 2;\n    Point[] p = new Point[count * count];\n\n    for (a = y = 0; y < count; y++)\n        for (x = 0; x < count; x++)\n            p[a++] = /* Create point here */\n    return p;\n}	0
13676444	13676387	WPF login authentication	var username = txtUserName.Text;\n   var password = txtPassword.Text;// there is available encryption on the web that you can use on. and your code will be like var password=enc.EncryptToString(txtPassword.Text);\n   var isValidUser = from user on UserTable\n                     where user.UserName == txtUserName.Text && user.Password == password && user.Status == 1\n                     select user;  \n   if(isValiduser.Count() > 0)\n   {\n     //OK you can log on\n   }\n   else\n   {\n     //user credential is invalid\n   }	0
14208767	14208721	Is there a more readable way of making a long chain of && statements?	if(IsAllowed)\n{\n   DoSomethingInteresting();\n}	0
14879532	14877722	How to set the value of nullable property using PropertyInfo.SetValue Method (Object, Object)	public static void ConvertBlToUi<TBl, TUi>(TBl entitySource, TUi entityTarget)\n    {\n        var blProperties = typeof(TBl).GetProperties().Select(p => new { Name = p.Name.ToLower(), Property = p }).ToArray();\n\n        var uiProperties = typeof(TUi).GetProperties().Select(p => new { Name = p.Name.ToLower(), Property = p });\n\n        foreach (var uiProperty in uiProperties)\n        {\n            var value = blProperty.Property.GetValue(entitySource);\n            var t = Nullable.GetUnderlyingType(uiProperty.Property.PropertyType) ?? uiProperty.Property.PropertyType;\n            var safeValue = (value == null) ? null : Convert.ChangeType(value, t);\n            uiProperty.Property.SetValue(entityTarget, safeValue);\n        }\n    }	0
20971950	20971845	Getting the same data into a buffer from TCP/IP server	public void FillBuf(object sender)\n{\n    var handler = (Socket)sender;\n\n    while (true)\n    {\n        // Note: use local variables here. You really don't want these variables\n        // getting mixed up between threads etc.\n        int received = 0;\n        byte[] bytes = new byte[512];\n\n        while (received < bytes.Length)\n        {\n            int block = handler.Receive(bytes, received, bytes.Length - received,\n                                        SocketFlags.None);\n            received += block;\n        }\n        que.Enqueue(bytes);\n    }\n}	0
15219955	15219792	C# GET Request and Parsing JSON	var client = new HttpClient();\n        var uri = new Uri("http://ponify.me/stats.php");\n        Stream respStream = await client.GetStreamAsync(uri);\n        DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(rootObject));\n        rootObject feed = (rootObject)ser.ReadObject(respStream);\n        System.Diagnostics.Debug.WriteLine(feed.SONGHISTORY[0].TITLE);	0
3046124	3045245	Silverlight Datagrid select on right click	private void dg_LoadingRow(object sender, DataGridRowEventArgs e)\n{\n    e.Row.MouseRightButtonDown += new MouseButtonEventHandler(Row_MouseRightButtonDown);\n}\nvoid Row_MouseRightButtonDown(object sender, MouseButtonEventArgs e)\n{\n    dg.SelectedItem = ((sender) as DataGridRow).DataContext;\n}	0
21105246	20247953	TripleDES implementation in Javascript different comparing with C#	if (useHashing){\n   key = CryptoJS.MD5(key).toString();\n   var k1 = key.substring(0, 16);\n   key = key + k1;\n}	0
380209	380171	regular expression for finding parts of a string within another	bool containsParts(string1, string2)\n{\n    count1 = array of 26 0's\n    count2 = array of 26 0's\n\n    // Note: be sure to check for an ignore non-alphabetic characters,\n    // and do case conversion if you want to do it case-insensitively\n    for each character c in string1:\n        count1[c]++\n    for each character c in string2:\n        count2[c]++\n\n    for each character c in 'a'...'z':\n        if count1[c] < count2[c]:\n            return false\n\n    return true\n}	0
5826598	5826559	How to process a file upload in ASP.NET with a form that does NOT have runat="server"?	runat="server"	0
26196400	26089931	Can PetaPoco poplulate a list of view models which contain multiple POCOs within each?	public partial class Character\n{\n    [ResultColumn]\n    public Entity Entity { get; set; }\n}\n\npublic partial class Entity \n{\n    [ResultColumn]\n    public Faction Faction { get; set; }\n}\n\nsql = Sql.Builder\n    .Append("SELECT c.*,e.*,f.*")\n    .Append("FROM [Character] c")\n    .Append("INNER JOIN [Entity] e ON e.Id = c.EntityId")\n    .Append("INNER JOIN [Faction] f ON f.Id = e.FactionId")\n    .Append("WHERE c.UserId = @0", 1);\n\nvar characters = db.Fetch<Character, Entity, Faction, Character>(\n    (c, e, f) => { c.Entity = e; e.Faction = f; return c; }, sql);	0
2010358	2010327	Problem seeing XML declaration on System.Console	XDocument xd = new XDocument(new XDeclaration("1.0", "utf-8", "yes"));\n  xd.Add(new XElement("top"));\n  xd.Save(Console.Out);	0
20405981	20405897	How to replace WHILE with Timer	private CancellationTokenSource ts = new CancellationTokenSource();\n\npublic void Start()\n{\n    System.Timers.Timer t = new System.Timers.Timer();\n    t.Interval = 200;\n    t.Elapsed += (s, e) =>\n    {\n        if (ts.Token.IsCancellationRequested)\n        {\n            // another thread decided to cancel\n            Debug.WriteLine("task canceled");\n            t.Stop();\n        }\n    }\n    t.Start();\n}\n\npublic void Stop()\n{\n    // Can't wait anymore => cancel this task \n    ts.Cancel();\n}	0
6190275	6182150	How can I stop cells from being entered when a datagridview row is selected by a row header click?	private void dataGridView1_RowStateChanged(object sender, DataGridViewRowStateChangedEventArgs e) {\n    if (e.StateChanged == DataGridViewElementStates.Selected) {\n        Console.WriteLine("TRUE");\n        dataGridView1.ReadOnly = true;\n    }\n}\n\nprivate void dataGridView1_CellStateChanged(object sender, DataGridViewCellStateChangedEventArgs e) {\n    if (e.StateChanged == DataGridViewElementStates.Selected) {\n        Console.WriteLine("false");\n        dataGridView1.ReadOnly = false;\n    }\n}	0
33482923	33482832	Passing C++ string to a c# function	//c++/clr\nvoid someCppFunc(){\n    long expected = 2;\n    long actual = 2;\n    Assert::AreEqual<long>(expected, actual, gcnew System::String(L"Some info message"));\n}	0
28717599	28716848	Null property value from Abstract class	public class SumObject\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n}\n\npublic abstract class AbstractClass\n{\n    protected SumObject SumProperty { get; private set; }\n\n    protected AbstractClass()\n    {\n        SetupSumObjecInAbstractClass();\n        DoWorkInChildClass();\n    }\n\n    protected void SetupSumObjecInAbstractClass()\n    {\n        SumProperty = new SumObject() { ID = 1, Name = "James Dean" };\n    }\n\n    protected abstract void DoWorkInChildClass();\n}\n\npublic class ChildClass : AbstractClass\n{\n    protected override void DoWorkInChildClass()\n    {\n        if (SumProperty == null)\n            throw new Exception("Dang!");\n\n        Console.WriteLine(string.Format("My Name is: {0}"\n                                        , SumProperty.Name));\n        Console.ReadKey();\n    }\n}\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var name = new ChildClass();\n    }\n}	0
13553228	13552939	How can i pull an image and data from a Database?	public BitmapImage ImageFromBuffer(Byte[] bytes)\n{\n    MemoryStream stream = new MemoryStream(bytes);\n    BitmapImage image = new BitmapImage();\n    image.BeginInit();\n    image.StreamSource = stream;\n    image.EndInit();\n    return image;\n}\n\npublic Byte[] BufferFromImage(BitmapImage imageSource)\n{\n    Stream stream = imageSource.StreamSource;\n    Byte[] buffer = null;\n    if (stream != null && stream.Length > 0)\n        {\n            using (BinaryReader br = new BinaryReader(stream))\n                {\n                    buffer = br.ReadBytes((Int32)stream.Length);\n                }\n        }\n\n    return buffer;\n}	0
565889	538946	Monitoring WLAN Radio Connection in Windows Mobile 6/C#	int key = (int)Registry.GetValue("HKEY_LOCAL_MACHINE\\System\\State\\Hardware", "WiFi", -1);	0
28648551	28648409	Count similar adjacent items in List<string>	static IEnumerable<Tuple<string, int>> FindAdjacentItems(IEnumerable<string> list)\n{\n    string previous = null;\n    int count = 0;\n    foreach (string item in list)\n    {\n        if (previous == item)\n        {\n            count++;\n        }\n        else\n        {\n            if (count > 1)\n            {\n                yield return Tuple.Create(previous, count);\n            }\n            count = 1;\n        }\n        previous = item;\n    }\n\n    if (count > 1)\n    {\n        yield return Tuple.Create(previous, count);\n    }\n}	0
28491402	28490713	VS 2010 debugging outlook RibbonExtensibility UI xml	File | Options | Advanced | Developers | Show add-in user interface errors	0
11611520	11611174	For testing I would like to generate a lot of files with some content - any easy way?	static void Main(string[] args)\n    {\n        int numFiles = 30;\n\n        for (int fileIndex = 0; fileIndex < numFiles; fileIndex++)\n        {\n            string randomFileName = Path.Combine(@"c:\temp", Path.GetRandomFileName() + ".csv");\n\n            GenerateTestFile(randomFileName, 20, 10);\n        }\n    }\n\n    static void GenerateTestFile(string fileName, int numLines, int numValues)\n    {\n        int[] values = new int[numValues];\n\n        Random random = new Random(DateTime.Now.Millisecond);\n        FileInfo f = new FileInfo(fileName);\n\n        using (TextWriter fs = f.CreateText())\n        {\n            for (int lineIndex = 0; lineIndex < numLines; lineIndex++)\n            {\n                for (int valIndex = 0; valIndex < values.Length; valIndex++)\n                {\n                    values[valIndex] = random.Next(100);\n                }\n\n                fs.WriteLine(string.Join(",", values));\n            }\n        }\n    }	0
30790777	30784957	C# WebMethod - Send and receive same custom object as parameter	public class Person\n    {\n\n        private string _Nome;\n        private string _Nascimento;\n\n        public string Nome { get { return _Nome; } set { _Nome = value; } }\n        public string Nascimento { get { return _Nascimento; } set { _Nascimento= value; } }\n\n        public Person()\n        {\n\n        }\n\n        public Person(string Nome, DateTime Nascimento)\n        {\n            _Nome = Nome;\n            _Nascimento = Nascimento.ToString();\n        }\n\n    }	0
16989090	16988846	Selenium WebDriver C# - difficulty switching from iFrame back to MainPage headings	WebElement el = (WebElement) ((JavascriptExecutor) driver).executeScript("return window.frameElement");	0
4249462	4249356	C# how to check if file is in folder according to object of filenames	public static Boolean CheckContents(string ExportDirectory, string DspFleName)\n    {\n        if (DspFleName == "None")\n            return true;\n\n        var DspFle = DspFleName.Split(',');\n        var ActualFiles = Directory.GetFiles(ExportDirectory);\n\n        foreach(var file in DspFle)\n            if (!ActualFiles.Any(x=>Path.GetFileName(x).Equals(file)))\n                return false;\n\n        return true;\n    }	0
1744677	1722905	FileLoadException with new version of dll	Assembly asm = Assembly.LoadFrom("XXX.YYY.ZZZ.Bin.dll");\nType type = asm.GetType("MyType");\nIMyType obj = Activator.CreateInstance(type) as IMyType;	0
13118805	13118782	Content of byte array	zero-indexed	0
31743539	31535192	how to use OnPageScrollStateChanged in xamarin	public class HomePageActivity : FragmentActivity, Android.Support.V4.View.ViewPager.IOnPageChangeListener\n    {\nprotected override void OnCreate (Bundle bundle)\n        {\n            base.OnCreate (bundle);\n\n            // Create your application here\n            SetContentView(Resource.Layout.home);\nvar viewPager_up = FindViewById<Android.Support.V4.View.ViewPager>(Resource.Id.viewPager_up);\nviewPager_up.AddOnPageChangeListener (this);\n\n}\npublic void OnPageScrollStateChanged (int state)\n        {\n            Console.WriteLine ("OnPageScrollStateChanged "+" "+state);\n        }\n        public void OnPageScrolled (int position, float positionOffset, int positionOffsetPixels){\nConsole.WriteLine ("OnPageScrolled "+" "+position);\n}\n\n        public void OnPageSelected (int position)\n        {\n            Console.WriteLine ("OnPageSelected"+" "+position);\n\n\n        }\n}	0
26888180	26888074	Try in finally block	try\n{\n    operation1();\n    operation2();\n    ...\n}\nfinally\n{\n    cleanup();\n}\n\npublic void cleanup() {\n    try\n    {\n        finalizer_operation1();\n        finalizer_operation2();\n\n    }\n    finally\n    {\n        very_critical_finalizer_operation_which_should_occurs_at_the_end();\n    }\n}	0
21348607	21348583	How to display the highest 3 array element in descending order?	var result = arrayname.Select((m, index) => new\n            {\n                key = array[index],\n                value = m\n            })\n                .OrderByDescending(m => m.key)\n                .Select(m => m.value)\n                .Take(3);\n\n\n   var textBoxValue = string.Join(" ", result);	0
11686953	11686761	How to read pages in a Word document (C#)	using System;\nusing Microsoft.Office.Interop.Word;\n\nnamespace PageSetup\n{\n    class TestPageOrientation\n    {\n        static void Main(string[] args)\n        {\n            var app = new Microsoft.Office.Interop.Word.Application();\n            app.Visible = true;\n\n            //Load Document\n            Document document = app.Documents.Open(@"C:\Temp\myDocument.docx");\n\n            document.PageSetup.Orientation = WdOrientation.wdOrientLandscape;\n        }\n    }\n}	0
34274813	34263643	use regex mongo c# to find in list	public async Task<List<ObjectId>> GetEntitiesIdsByEmail(IList<string> emails)\n{\n     var regexFilter = "(" + string.Join("|", emails) + ")";\n     var projection = Builders<Entity>.Projection.Include(x => x.Id);\n     var filter = Builders<Entity>.Filter.Regex("Email",\n           new BsonRegularExpression(new Regex(regexFilter, RegexOptions.IgnoreCase | RegexOptions.IgnorePatternWhitespace)));\n     var entities = await GetCollection().Find(filter).Project(projection).ToListAsync();\n     return entities.Select(x=>x["_id"].AsObjectId).ToList();\n}	0
1607549	1597404	Using Spark View Engine in a stand alone application	// Create an engine using the templates path as the root location\n    // as well as the shared location\n    var engine = new SparkViewEngine\n        {\n             DefaultPageBaseType = typeof(SparkView).FullName,\n             ViewFolder = viewFolder.Append(new SubViewFolder(viewFolder, "Shared"))\n        };\n\n    SparkView view;\n\n    // compile and instantiate the template\n    view = (SparkView)engine.CreateInstance(\n                          new SparkViewDescriptor()\n                              .AddTemplate(templateName));\n\n    // render the view to stdout\n    using (var writer = new StreamWriter(Console.OpenStandardOutput(), Encoding.UTF8))\n    {\n        view.RenderView(writer);\n    }	0
3199113	3199089	Matching a string that starts with a specific character	(?<=~)[^\s]+	0
5584818	5584746	Datagridview does not showing data	List<GmailItem> lstMail = new List<GmailItem>();\n        for (int i = 0; i < mailCount; i++)\n        {\n            lstMail.Add(client.GetMailItem(i));\n        }\n\n        _bindingMails.DataSource = lstMail;\n        dgMails.DataSource = _bindingMails;	0
15036596	15036584	Lambda expression for multiple parameters	Func<int, int, int> Add = (x, y) => x + y;\n\nFunc<int, int, int> diff = (x, y) => x - y;\n\nFunc<int, int, int> multi = (x, y) => x * y;	0
17418906	17418820	Implementing a loop using a timer in C#	Timer r = new System.Timers.Timer(timeout_in_ms);\nr.elapsed += new ElapsedEventHandler(timer_Elapsed);\nr.Enabled = true;\nrunning = true;\nwhile (running) {\n   // do stuff\n}\nr.Enabled = false;\n\nvoid timer_Elapsed(object sender, ElapsedEventArgs e)\n{\n   running = false;\n}	0
20018496	20018373	How to get updated table names in sql server?	sqlAdapter = new SqlDataAdapter("SELECT * FROM " + saka[listboxselectedindex]+" where stts=@sttsValue", conn);\nsqlAdapter.SelectCommand.Parameters.AddWithValue("@sttsValue",1);\n            dataset = new DataSet();\n            sqlAdapter.Fill(dataset, saka[listboxselectedindex]);\n            datagridview1.DataSource = null;\n            datagridview1.DataSource = dataset.Tables[saka[listboxselectedindex]];	0
54888	54833	Prevent Multi-Line ASP:Textbox from trimming line feeds	public void btnSubmitClick(object sender, EventArgs e)\n{\n    if (this.txtMultiLine.Text.StartsWith("\r\n"))\n    {\n        this.txtMultiLine.Text = "\r\n" + this.txtMultiLine.Text;\n    }\n}	0
17182572	17182534	Extracting image link through regex in C#	url = url.Replace("[IMG]", "").Replace("[/IMG]");	0
4095269	4081039	Telerik RadCaptcha / How Can We Validate RadCaptcha From Code Behind / WithOut Using Validation Group	RadCaptcha1.Validate();\nPage.Validate();\n\nif(RadCaptcha1.IsValid)\n{\n     //TODO: Add your logic here\n}	0
1680353	1680323	How can I turn this 12-line method into a 1-line LINQ expression?	var s = string.Join(", ", files.Select(file => Path.GetExtension(file))\n    .Distinct(StringComparer.InvariantCultureIgnoreCase).ToArray());	0
10707982	10706856	Bind Inner Grid in Nested RadGrid from CodeBehind	protected void RowBound(object sender, GridItemEventArgs e)\n{\n   if (e.Item is GridNestedViewItem)\n   {\n      GridNestedViewItem item = e.Item as GridNestedViewItem;\n   }\n}	0
14001579	14001493	How can I send email reminders to the registered uses in the selected event from GridView?	for (int userIndex = 0; userIndex < addressList.Count-1; userIndex++)\n                {	0
32701478	32700806	How to measure the exact time to load a page using selenium or in C#?	waitForJavaScript("(typeof Ajax == 'undefined' ? jQuery.active == 0 : Ajax.activeRequestCount == 0)")	0
22341431	22341285	Array replace matching value with another array value. C#	var a = "12345";\nvar c = "54321";\nvar e = "0A9B8C7D6E5F4G3H2I1";\n\n// create a mutable copy of e\nvar builder = new StringBuilder(e);\nfor (var i = 0; i < e.Length; ++i) // for each character position in e\n{\n    // look for that character in a\n    var index = a.IndexOf(e[i]);\n    // if we found it, replace the character at that position with the\n    // corresponding character from c\n    if (index >= 0) { builder[i] = c[index]; }\n}\nvar result = builder.ToString(); // 0A9B8C7D6E1F2G3H4I5	0
13356301	13355897	While adding rows to datagridview, no values are inserted except last row	rowIndex = this.searchDataGridView.Rows.Add();	0
7308123	7308105	Relocating items in a list	var temp = list[1];\nlist[1] = list[3];\nlist[3] = temp;	0
19487177	19451933	WebAPI List<T> Serialization XML/JSON output	public class ListWrapper<T>\n{\n    public ListWrapper(INamedEnumerable<T> list)\n    {\n        List = new List<T>(list);\n        Name = list.Name;\n    }\n\n    public List<T> List { get; set; }\n\n    public string Name { get; set; }\n}	0
27860289	27859701	Getting Body content from MSMQ	message.Formatter = new BinaryMessageFormatter();\nvar reader = new StreamReader(message.BodyStream, Encoding.Unicode);\nvar msgBody = reader.ReadToEnd();	0
8833904	8833793	Want to use C# ? FtpWebResponse? to read file list from FTP, but it returns HTML	reqFTP.Proxy = GlobalProxySelection.GetEmptyWebProxy();	0
16661253	16661200	Sum of Columns of Two Tables in LINQ	var roomAmount = dc.Room.Single(r => r.RoomId == myRoomId).RoomCost;\nvar itemAmount = dc.RoomItem.Where(i => i.RoomId == myRoomId).Sum(r => r.ItemCost);\n\ntxtTotalAmount.Text= roomAmount + itemAmount ;	0
1633084	1632969	Search order of HttpRequest indexer	public string this[string key]\n{\n    get\n    {\n        string str = this.QueryString[key];\n        if (str != null)\n        {\n            return str;\n        }\n        str = this.Form[key];\n        if (str != null)\n        {\n            return str;\n        }\n        HttpCookie cookie = this.Cookies[key];\n        if (cookie != null)\n        {\n            return cookie.Value;\n        }\n        str = this.ServerVariables[key];\n        if (str != null)\n        {\n            return str;\n        }\n        return null;\n    }\n}	0
21086799	21086751	Start a new activity	Intent intent= new Intent(this.ApplicationContext, typeof(AutoLinkActivity));	0
16642649	16631753	Convert Unicode string made up of culture-specific digits to integer value	string ToLatinDigits(string nativeDigits)\n    {\n        int n = nativeDigits.Length;\n        StringBuilder latinDigits = new StringBuilder(capacity: n);\n        for (int i = 0; i < n; ++i)\n        {\n            if (char.IsDigit(nativeDigits, i))\n            {\n                latinDigits.Append(char.GetNumericValue(nativeDigits, i));\n            }\n            else if (nativeDigits[i].Equals('.') || nativeDigits[i].Equals('+') || nativeDigits[i].Equals('-'))\n            {\n                latinDigits.Append(nativeDigits[i]);\n            }\n            else\n            {\n                throw new Exception("Invalid Argument");\n            }\n        }\n        return latinDigits.ToString();\n    }	0
6378961	6378875	How to use RegEx in C# to take all the matching strings into a collection	var srcString = @"foo foo %%match1%%, foo %%match2%%, %%match3%% foo foo";\n\nIEnumberable<string> results = Regex.Matches(srcString, @"\%\%(.*?)\%\%").Cast<Match>().Select(match => match.Value);	0
4624392	4064125	C# Copy selected text from richtextbox	string text = "Summary:" + Environment.NewLine + this.richTextBoxSummary.Text;\nClipboard.SetText(text);	0
15814240	15814193	Can you initialize an abstract class so you can set it equal to a child class later?	BaseAnimal myAnimal;\n\nif (someVar) {\n    var myCat = new cat();\n\n    // Do things with myCat that are cat-specific.\n\n    myAnimal = myCat;\n} else {\n    var myDog = new dog();\n\n    // Do things with myDog that are dog-specific.\n\n    myAnimal = myDog;\n}\n\nallAnimals.add(myAnimal);	0
1465740	1465715	How to I find specific generic overload using reflection?	MethodInfo GetMethod(Type argType, Type returnType)\n{\n    var enumerableType = typeof(IEnumerable<>).MakeGenericType(new Type[] { argType });\n    Console.WriteLine(enumerableType);\n    var methods = from method in typeof(Enumerable).GetMethods(BindingFlags.Public | BindingFlags.Static)\n      let parameters = method.GetParameters()\n      let genParams = method.GetGenericArguments()\n      where method.Name == "Average" &&\n      method.ContainsGenericParameters &&                              \n      parameters.Length == 2 &&\n      parameters[1].ParameterType.GetGenericTypeDefinition() == typeof(Func<,>) &&\n      parameters[1].ParameterType.GetGenericArguments()[1] == argType &&\n      method.ReturnType == returnType\n      select method;\n\n      return methods.FirstOrDefault();\n}	0
8480991	8480875	How to replace an element in a LinkedList?	LinkedList<int> ll;\nll.Find(2).Value = 3;	0
1744994	1744967	In C#, is there a way to write custom object initializers for new data-types?	Test test = new Test() {\n    new Test2() {\n    new Test3() {\n\n    }\n    },\n    new Test() {\n    new Test2() {\n    { new Test(), new Test2() },\n    { new Test(), new Test2() },\n    { new Test(), new Test2() }\n    }\n    }\n};\n\npublic class Test : IEnumerable\n{\n    public void Add(Test a){}\n    public void Add(Test2 a){}\n    public IEnumerator GetEnumerator(){}\n}\n\npublic class Test2 : IEnumerable\n{\n    public void Add(Test a, Test2 b){}\n    public void Add(Test3 a){}\n    public IEnumerator GetEnumerator(){}\n}\n\npublic class Test3 : IEnumerable\n{\n    public void Add(Test a){}\n    public void Add(Test2 a){}\n    public IEnumerator GetEnumerator(){}\n}	0
30236429	30236288	How to open page in new tab from GridView?	protected void lnk_Click(object sender, EventArgs e)\n {\n      LinkButton lnk = sender as LinkButton;\n      Label Label1 = lnk.NamingContainer.FindControl("Label1") as Label;\n\n      if (Label1.Text == "Alert1")\n      {\n          Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert1.aspx','_blank');", true);\n      }\n      else if (Label1.Text == "Alert2")\n      {\n          Page.ClientScript.RegisterStartupScript(this.GetType(), "OpenWindow", "window.open('alert2.aspx','_blank');", true);\n      }\n }	0
10461978	10461257	an attempt was made to access a socket in a way forbbiden by it's access permissions. why?	netstat -o	0
23510630	23509663	Extracting substring from string using html tags	string pattern = @"<p\sclass=""([a-zA-Z]*)"">(.*?)</p>";\nRegex r = new Regex(pattern, RegexOptions.None);\nstring s = @"...";\n\nforeach (Match m in r.Matches(s))\n{\n   ...\n}	0
11344655	11344591	Linq to compare two collections in C#	OrgCollection myYears = Org.RetrieveDistinctYear();\nAcademicYearCollection allYears = AcademicYear.RetrieveAll();\n\nvar items = from y in myYears\n            join ay in allYears\n            on y.Code equals ay.AcademicYearCode\n            select new { ay.Name, ay.Code }	0
27631358	27631151	How to split a dictionary into "n" parts	// remove OrderBy if ordering is not important\nvar ordered = dictionary.OrderBy(kv => kv.Key);\nvar half = dictionary.Count/2;\nvar firstHalf = ordered.Take(half).ToDictionary(kv => kv.Key, kv => kv.Value);\nvar secondHalf = ordered.Skip(half).ToDictionary(kv => kv.Key, kv => kv.Value);	0
25976288	25975130	c# webdriver - how can I verify 'disabled' attribute exists for a button	IWebElement button = locator to button;\nbutton.getAttribute("disabled");	0
12960716	12958848	Azure table storage range query with commonly used condition wrapped in method	public static Expression<Func<MyEntity, bool>> HasPrefix(String prefix) \n{ \n    return e => e.RowKey.CompareTo(prefix + '_') > 0 && e.RowKey.CompareTo(prefix + '`') <= 0;\n}\n\nCloudTableQuery<MyEntity> query =\n    (from e in tableServiceContext.CreateQuery<MyEntity>(tableName)\n    where e.PartitionKey == "KnownPartition"\n    select e)\n    .Where(HasPrefix("Prefix"))\n    .AsTableServiceQuery();	0
11724977	11724884	How to add 'ff ff ff ff' (HEX) before the data of an byte[] array?	byte[] firstArray = new byte[] {0xFF,0xFF,0xFF,0xFF}; \nbyte[] secondArray = [your data here]\nbyte[] result = firstArray.Concat(secondArray).ToArray();	0
9844367	9844265	Regular Expression for last folder in path	var directoryname = new DirectoryInfo(@"C:\Projects\Test").Name;\n\\The variable directoryname will be Test	0
27856326	27856123	Get distinct objects from list of dynamic objects	List<dynamic>	0
7031547	7031414	Strange Issues with datagrid in wpf	height = DataGridHeight - Height of all rows except last one	0
8557455	8557392	How can I derive from a base class and implement an interface in C#?	interface ITestInterface\n{\n    void Test();\n    string Test2();\n}\n\npublic class TestBase : ITestInterface\n{\n    #region ITestInterface Members\n\n    public void Test()\n    {\n        System.Console.WriteLine("Feed");\n    }\n\n    public string Test2()\n    {\n        return "Feed";\n    }\n\n    #endregion\n}\n\npublic class TestChild : TestBAse, ITestInterface\n{\n    public void Test()\n    {\n        System.Console.WriteLine("Feed1");\n    }\n}\n\npublic static void Main(){\n    TestChild f = new TestChild();\n    f.Test();\n\n    var i = f as ITestInterface;\n\n    i.Test();\n    i.Test2();//not implemented in child but called from base.\n}	0
13903844	13902781	How to create WCF proxy without svc file which is hosted in windows apps	net.tcp://localhost:7996/WPFHost/mex	0
14241158	14241102	Run command through a c# socket	Process::Start()	0
13864447	13864272	How to count the number of distinct items over multiple many-to-many table relationships?	int count = costumer.GroupCustomers\n    .SelectMany(gc => gc.Group.GroupEmployees)\n    .Select(ge => ge.EmployeeID)\n    .Distinct()\n    .Count();	0
12898735	12898616	One instance application over multiple Windows user accounts	mutexName = String.Format("Global\\{{{0}}}", "Application Name");	0
27310	27294	Abstract Factory Design Pattern	public Task CreateTask(XmlElement elem)\n{\n    if (elem != null)\n    { \n        try\n        {\n          Assembly a = typeof(Task).Assembly\n          string type = string.Format("{0}.{1}Task",typeof(Task).Namespace,elem.Name);\n\n          //this is only here, so that if that type doesn't exist, this method\n          //throws an exception\n          Type t = a.GetType(type, true, true);\n\n          return a.CreateInstance(type, true) as Task;\n        }\n        catch(System.Exception)\n        {\n          throw new ArgumentException("Invalid Task");\n        }\n    }\n}	0
11556763	11555534	Reading from a stream with mixed XML and plain text	using System;\nusing System.Linq;\nusing System.Xml;\n\nstatic class Program {\n\n    static void Main(string[] args) {\n\n        string mixed = @"\nFound two objects:\nObject a\n<object>\n    <name>a</name>\n    <description></description>\n</object>\nObject b\n<object>\n    <name>b</name>\n    <description></description>\n</object>\n";\n        string xml = "<FOO>" + mixed + "</FOO>";\n        XmlDocument doc = new XmlDocument();\n        doc.LoadXml(xml);\n        var xmlFragments = from XmlNode node in doc.FirstChild.ChildNodes \n                           where node.NodeType == XmlNodeType.Element \n                           select node;\n        foreach (var fragment in xmlFragments) {\n            Console.WriteLine(fragment.OuterXml);\n        }\n\n    }\n\n}	0
22634349	22633767	Remove object once clicked c#	private void redballoon_click(object sender, MouseButtonEventArgs e)\n{\n    //react only when baloon is clicked by left mouse button\n    if (e.LeftButton != MouseButtonState.Pressed)\n        return;\n\n    string red_balloon_question = System.Windows.Browser.HtmlPage.Window.Prompt("Question 5X2");\n\n    if (red_balloon_question == "10")\n    {\n        MessageBox.Show("Well done that is correct, you gain 1 point", "Correct Answer", MessageBoxButton.OK);\n        PopBalloonCount++;             \n    }\n    else\n    {\n        MessageBox.Show("Incorrect, you loose 1 point", "Wrong Answer", MessageBoxButton.OK);\n        PopBalloonCount--;\n    }\n\n    score.Content = "Your Score" + " " + Convert.ToString(PopBalloonCount);\n    this.lastBalloonClickColor = "red_balloon"; // register the last click\n\n    //hide baloon\n    redballoon.Visibility = Visibility.Hidden;\n    //or\n    redballoon.Opacity = 0.0;\n}	0
185580	185445	FileLoadException on windows 2003 for managed c++ dll	depends.exe	0
17095648	17095434	Creating text file with given content entered in richtextbox but it shrinks all text	richTextBox1.SaveFile("Test.txt or your file path",RichTextBoxStreamType.PlainText);	0
11366931	11366600	How do you tell if a Windows Form is open but behind another window?	this.TopMost = true;\nthis.Focus();\nthis.BringToFront();\nthis.TopMost = false;	0
3875435	3875296	How do I ensure the value of property for others that are dependent upon it?	get\n{\n   if (Math.Abs(value) > 1 && this.PayoutType == CutType.Percent)\n   {\n      return _payout /100;\n   }\n   return _payout;\n}\nset{_payout = value;}	0
7054898	7054885	List of strings wont get written completely to text file	Using{}	0
15007716	15007660	AutoMapper and convert a datetime to string	Mapper.CreateMap<I_NEWS, NewsModel>().ForMember(x => x.DateCreated,\n  opt => opt.MapFrom(src => ((DateTime)src.DateCreated).ToShortDateString()));	0
26573403	26550915	Multiple results with many-to-many relationship dapper	public List<Item> GetAll()\n    {\n        var sql =\n            "SELECT * FROM Items;" +\n            "SELECT ItemId, Tags.Title FROM ItemTag left join Tags on ItemTag.TagId = Tags.Id;";\n\n        using (var multipleResults = this.db.QueryMultiple(sql))\n        {\n            var items = multipleResults.Read<Item>().ToList();\n            var tags = multipleResults.Read<Tag>().ToList();\n\n            var tagsByItemId = tags.ToLookup(t => t.ItemId);\n\n            foreach (var item in items)\n            {\n                item.Tags = tagsByItemId[item.Id].ToList();\n            }\n\n            return items;\n        }\n    }	0
5102798	5102760	WPF button click in C# code	Button btn = new Button();\nbtn.Name = "btn1";\nbtn.Click += btn1_Click;\n\nprivate void btn1_Click(object sender, RoutedEventArgs e)\n{\n    // do something\n}	0
23647043	23646879	Hide the second ComboBox(Collapse) on selecting a item from first Combo Box	private Visibility _comboboxvisibility;\n\n   public Visibility comboboxvisibility\n   {\n       get { return _comboboxvisibility; }\n       set { _comboboxvisibility = value; RaisePropertyChanged("comboboxvisibility"); }\n   }\n\n   private XyZListItem _selectedItem;\n\n   public XyZListItem SelectedItem\n   {\n       get { return _selectedItem; }\n       set {\n           comboboxvisibility = Visibility.Collapsed;         \n    }\n   }	0
10585651	10585594	How To Get "Find Usages" working with implicit operator methods?	[Obsolete]	0
13439162	13438832	Writing files to Temp Path creates random named folders	Path.GetTempPath()+"sdhfuisdhfusdhc";	0
29445786	29443531	send data via GPRS in C# 3.5	private void SendData(string value)\n    {\n        byte[] data = Encoding.ASCII.GetBytes(value);\n        try\n        {\n            using (TcpClient client = new TcpClient("31.47.53.12", 2036))\n            {\n                NetworkStream stream = client.GetStream();\n                stream.Write(data, 0, data.Length);\n            }\n        }\n        catch (Exception err)\n        {\n\n        }	0
26253221	26252894	Filter Query with extension method in group by context	Dim months = {1, 2}\nDim query = From row In DataSet.A\n            Where row.Position <> 5 AndAlso months.Contains(row.Date.Month)\n            Group row By name Into eGroup = Group\n            Select New With {\n                Key .Name = name,\n                .Amount = eGroup.Count(Function(row) row.Field(Of Decimal)("Money"))\n            }	0
10048695	10048613	Capturing video with opencv	VideoCapture cap (0);	0
31482309	31482052	How can I access specific index in a list at a particular key inside a dictionary	int i = 42; // Or whatever index you want to look up\nDateTime date = DATE_YOU_WANT_HERE;\n\nList<double> valuesForDate;\n\nbool foundDate = sortedDict.TryGetValue(date, out valuesForDate);\nif (foundDate)\n{\n    double theValue = valuesForDate[i];\n}\nelse\n{\n    // Whatever you need to do if there is no key for your date\n}	0
22169622	22169454	Convert string date to datetime	DateTime dt = DateTime.ParseExact("Mar 08 1969 12:00AM","MMM dd yyyy hh:mmtt",CultureInfo.InvariantCulture);	0
18113368	18113278	Populate a datagridview with sql query results	string select = "SELECT * FROM tblEmployee";\n Connection c = new Connection();\n SqlDataAdapter dataAdapter = new SqlDataAdapter(select, c.con); //c.con is the connection string\n\n SqlCommandBuilder commandBuilder = new SqlCommandBuilder(dataAdapter);\n DataSet ds = new DataSet();\n dataAdapter.Fill(ds);\n dataGridView1.ReadOnly = true; \n dataGridView.DataSource = ds.tables[0];	0
29241576	29241416	Unable to extract string between double quotes using regex	"(.+?)"	0
24311556	24310445	Make NumericUpDown accepts both comma and dot as decimal separator	private void numericUpDown1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if (e.KeyChar.Equals('.') || e.KeyChar.Equals(','))\n        {\n            e.KeyChar = ((System.Globalization.CultureInfo)System.Globalization.CultureInfo.CurrentCulture).NumberFormat.NumberDecimalSeparator.ToCharArray()[0];\n        }\n    }	0
20946031	20945974	Syntax error in insert into statement in C#. While inserting the values to access	insert into book ([Book Name],Description)	0
20828680	20828600	Problems adding data into a datatable C#	INSERT INTO DictionaryTest (BinNumber,Letter) VALUES (@NewCode,@NewLetter)	0
2613022	2613009	All Audio frequencies	sqrt(re * re + im * im)	0
19326584	19326555	Combine string[] to string	string joined = String.Join(sOperators, Operators);	0
26671327	26670794	Creating a continuously running application with a switch statement	string command;\ndo\n{\n    command = Console.ReadLine();\n}\nwhile(!"3".Equals(command, StringComparison.InvariantCultureIgnoreCase))	0
20057419	19027321	Getting underlying object C# by passing in a string at runtime	public object ReturnValue(string operationName, object returnValue)\n{\n    Type t = returnValue.GetType();\n    return Activator.CreateInstance(t);\n}	0
13126335	13126238	HTML find and replace href tags	HtmlDocument doc = new HtmlDocument();\n        doc.Load(myHtmlFile); // load your file\n\n        // select recursively all A elements declaring an HREF attribute.\n        foreach (HtmlNode node in doc.DocumentNode.SelectNodes("//a[@href]"))\n        {\n            node.ParentNode.ReplaceChild(doc.CreateTextNode(node.InnerText + " <" + node.GetAttributeValue("href", null) + ">"), node);\n        }\n\n        doc.Save(Console.Out); // output the new doc.	0
280470	280449	Refactoring solution needed	private Control GetControl()\n{\n    string dynamicCtrl = CurrentItem.DynamicControl;\n    string path = SomeClass.DynamicControls[dynamicCtrl];\n\n    Control ctrl = LoadControl(path);    \n\n    return ctrl;\n}	0
19976251	19975964	How can I pass values from Entity Layer to Presentation Layer	protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n        {\n            switch (e.CommandName)\n            {\n                case "click":\n                    {\n                        // Populate Person Details                        \n                        PersonBL objPersonBL = new PersonBL();\n                        var objPerson = objPersonBL.GetPersonSingleByPersonID(e.CommandArgument.ToString());\n\n                        //Person objPerson = new Person();\n                        if (objPerson.Count != 0)\n                        {\n                            txtPersonID.Text = objPerson[0].PersonID;\n                            txtFirstname.Text = objPerson[0].Firstname;\n                            txtLastname.Text = objPerson[0].Lastname;\n                            break;\n                        }\n                    }\n                default:\n                    break;\n            }\n        }	0
12467416	12467184	Memory usage with winform app	stripevents(AddressOf Any_Control_ValChanged)\n    stripevents(AddressOf Any_EnterControl)\n    stripevents(AddressOf Any_LeaveControl)\n    stripevents(AddressOf ButtonClick)\n\nSub stripevents(ByVal eh As EventHandler)\n    [Delegate].RemoveAll(eh, eh)\nEnd Sub	0
24526372	24526337	remove duplicate from ObservableCollection<T>	myItems = new ObservableCollection<DateTime>(myItems.Distinct());	0
1815325	1815312	C# Generics, Constrain to Specific Structs	string Add<T>(object value, T expiration) where T : struct, IMyInterface	0
31311554	31311502	How do I define columns for inner DataGrid in a custom control	public static readonly DependencyProperty GridColumnsProperty = DependencyProperty.Register("GridColumns", typeof(ObservableCollection<DataGridColumn>), typeof(XGrid));\n        public ObservableCollection<DataGridColumn> GridColumns\n        {\n            get { return (ObservableCollection<DataGridColumn>)GetValue(GridColumnsProperty); }\n            set { SetValue(GridColumnsProperty, value); }\n        }\n\n\npublic XGrid()\n{\n        GridColumns = new ObservableCollection<DataGridColumn>();\n        GridColumns.CollectionChanged += (x, y) =>\n            {\n                dataGrid.Columns.Clear();\n                foreach (var column in this.GridColumns)\n                {\n                    dataGrid.Columns.Add(column);\n                }\n            };\n        InitializeComponent();\n    }	0
608889	608684	Word automation find out if a bookmark is in a table	Sub BookmarksInTables()\n    Dim aTable As Table\n    Dim aBookmark As Bookmark\n\n    For Each aBookmark In ActiveDocument.Bookmarks\n        For Each aTable In ActiveDocument.Tables\n            'If start of book mark is inside the table range or\n            ' the end of a book mark is inside the table range then YES!\n            If (aBookmark.Range.Start >= aTable.Range.Start _\n                And aBookmark.Range.Start <= aTable.Range.End) _\n            Or (aBookmark.Range.End >= aTable.Range.Start _\n                And aBookmark.Range.End <= aTable.Range.End) Then\n                MsgBox aBookmark.Name + " is inside a table"\n            Else\n                MsgBox aBookmark.Name + " is not inside a table"\n            End If\n        Next\n    Next\nEnd Sub	0
18962024	18961905	I need to write console application which runs once in every month	File -> New -> Project -> C# (Language) -> Console Application	0
1455323	1455281	LINQ: Prefetching data from a second table	var results = (from c in _customers\n               from ct in _customerTypes \n               where c.TypeId == ct.TypeId \n               select new\n                      {\n                         Customer = c,\n                         TypeName = ct.TypeName\n                      }).ToList();	0
1420874	1420859	Assigning to static readonly field of base class	public class ClassA\n{\n    public virtual string ProcessName { get { return "ClassAProcess"; } }\n} \n\npublic class ClassB : ClassA\n{\n    public override string ProcessName { get { return "MyProcess.exe"; } }\n}	0
21593556	21593482	Get value of non-existing variables by calling a method	public class MyDynamicObject : DynamicObject {\n    public override bool TryGetMember(GetMemberBinder binder, out Object result){\n        if (binder.Name == "myVar"){\n            result = "xyz";\n            return true;\n        }           \n\n        result = null;\n        return false;\n    }\n}\n\n// Usage\ndynamic x = new MyDynamicObject();\nConsole.WriteLine (x.myVar); // will output "xyz"	0
13484077	13483860	Generating a Crystal Report document with NHibernate	public IDataReader ExecuteReaderStoredProcedure(string procName, IUnitOfWork uow, IEnumerable<KeyValuePair<string, object>> parameters)\n    {\n        var command = Sessions[uow].Connection.CreateCommand();\n\n        command.CommandText = procName;\n        command.CommandType = CommandType.StoredProcedure;\n        foreach (var param in parameters)\n        {\n            var parameter = command.CreateParameter();\n            parameter.ParameterName = param.Key;\n            parameter.Value = param.Value;\n            command.Parameters.Add(parameter);\n        }\n\n        Sessions[uow].Transaction.Enlist(command);\n        return command.ExecuteReader();\n    }	0
6315453	6312636	How to implement catching and showing the current key presses using a WPF TextBox?	string keys = "";\n\n        if ((Keyboard.Modifiers & ModifierKeys.Control) > 0)\n        {\n            keys += "Control + ";\n        }\n\n        if ((Keyboard.Modifiers & ModifierKeys.Alt) > 0)\n        {\n            keys += "Alt + ";\n        }\n\n        if ((Keyboard.Modifiers & ModifierKeys.Shift) > 0)\n        {\n            keys += "Shift + ";\n        }\n\n        keys += e.Key;\n\n        YourTextBox.Text = keys;	0
19965396	19964311	Fetching Outlook email body	// change this in your code\nbody.Text = row["urn:schemas:httpmail:textdescription"].ToString();\n\n// To this\nMicrosoft.Office.Interop.Outlook.MailItem mailItem =\n                             myApp.Session.GetItemFromID(row["EntryID"]);\nbody.Text = mailItem.Body;	0
12076241	12076030	BackgroundWorker with a Recursive Function	void RecursiveLoop(BackGroundWorker worker)\n{\n  // ON entry check if we need to stop\n  if (worker.CancellationPending) return;\n  //\n  // Normal code and the recursion\n  if (morework) RecursiveLoop(worker);\n}	0
22180203	22175108	How to register type as specific interface by scanning local exe or assembly	builder.RegisterAssemblyTypes(dataAccess)\n         .Where(t => (typeof(INotifier).IsAssignableFrom(t) && t.IsClass && !t.IsAbstract))\n         .AsSelf()\n         .AsImplementedInterfaces();	0
30097674	30097050	Canvas in ImageView	// 2000x2000 is VERY large for an Android bitmap - consider using a smaller size?\n// You may see out of memory errors with this size.\nBitmap bitmap = Bitmap.CreateBitmap(2000, 2000, Bitmap.Config.Argb8888);\nCanvas canvas = new Canvas(bitmap);\ncanvas.drawPath(path, paint);\nimageView.setImageBitmap(bitmap);	0
7853952	7853939	C# - How do you display Apr '11 with DateTime.ToString	new DateTime(2011, 10, 1).ToString("MMM \\'yy")	0
30542699	30542571	C# Parsing a long date	string str = "Fri May 29 2015 00:00:00 GMT-0700 (Pacific Daylight Time)";\n DateTime dt = new DateTime();\n bool b = DateTime.TryParseExact(str.Substring(0,33), "ddd MMMM dd yyyy hh:mm:ss 'GMT'zzz", null, DateTimeStyles.None, out dt);	0
5269143	5268921	Select a particular value from datatable-C#	string expression;\n    expression = "NameColumn = 'John'";\n    DataRow[] foundRows;\n\n    // Use the Select method to find all rows matching the filter.\n    foundRows = table.Select(expression);\n\n    // Print column 0 of each returned row.\n    for(int i = 0; i < foundRows.Length; i ++) {\n        // List out the retreived values.\n        Console.WriteLine(foundRows[i]["ValueColumn"]);\n    }	0
7684803	7683911	get non-rotated rectangle just big enough to enclose rotated rectangle	GeneralTransform transform = yourRect.TransformToVisual(yourCanvas);\nRect bounds = transform.TransformBounds(new Rect(0,0, yourRect.ActualWidth, yourRect.ActualHeight));	0
3821431	3821399	Split string to List<string> with Linq	var str = "AAAA,12,BBBB,34,CCCCC,56";\n\nvar spl = str.Split(',');\nvar l1 = spl.Where((x, y) => y % 2 == 0).ToList();\nvar l2 = spl.Where((x, y) => y % 2 == 1).ToList();	0
34285599	34267898	Define range to text inside table cell	rng.MoveEnd Microsoft.Office.Interop.Word.WdUnits.wdCharacter, -1\nrng.Select(); // this line is useful to see the range where bookmark will be placed\nrng.Bookmarks.Add("BookmarkName", rng);	0
13383571	13381979	Upgrading the serializer for an XML file	XmlAttributeOverrides xmlAttributeOverrides = new XmlAttributeOverrides();\n\n//Add overrides to xmlAttributeOverrides, use sample from internet\n\nXmlSerializer serializer = new XmlSerializer(typeof(Data), XmlAttributeOverrides);	0
22999363	22999213	Accessing panels with similar names	Panel polje1 = new Panel() { Name = "polje1" };\nthis.Controls.Add(polje1);\nif (this.Controls.ContainsKey("polje1")) {\n  this.Controls["polje1"].BackColor = Color.Red;\n}	0
21550801	21550412	outer Join in linq with lambda expression	var details= (from p in repository.Query<Model.ProfileType>()\n             join r in repository.Query<Model.RoleProfile>() on p.Id equals r.ProfileTypeId into g\n             from x in g.DefaultIfEmpty()\n             select new RoleProfileModel{\n                    ProfileType=p.Name,\n                    SecurityLevel=x==null?string.Empty:x.SecurityLevel,\n                    ProfileCode=x==null?string.Empty:x.Code,\n}).ToArray();	0
1653685	1653001	How to encode Video from Web-Camera into H.264 in C#?	Video Source => Demux -> Audio Stream + Video Stream -> MP4Muxer	0
20865079	20864256	How to use a global array in C#?	public static class myGlobalArray\n{\n    public static int[] thisIsMyGlobalArray { get; set; }\n}	0
27379001	27317552	Match String with the Class property Names	Properties p = new Properties();\n        Type tClass = p.GetType();\n        PropertyInfo[] pClass = tClass.GetProperties();\n\n        int value = 0; // or whatever value you want to set\n        foreach (var property in pClass)\n        {\n            property.SetValue(p, value++, null);\n        }	0
16347610	16347378	SPROC insert with ExecuteNonQuery and ExecuteScalar	SET NOCOUNT ON;	0
11195540	11195494	How do I update a view model from an edit page in MVC3?	[HttpPost]\n    public ActionResult Edit(ClientContactViewModel model)\n    {\n        if (ModelState.IsValid)\n        {\n            ClientContact contact = db.ClientPersons.Include("Person")\n                                    .Where(x => x.ClientPersonId == model.ClientPersonId)\n                                    .SingleOrDefault();\n            contact.FirstName = model.FirstName;\n            // etc\n            db.Entry(contact).State = EntityState.Modified;\n            db.SaveChanges();\n            return RedirectToAction("Index");\n        }\n        return View(model);\n    }	0
14655182	14654693	Can I convert a string to a resource location in C#?	BackgroundImage = (Image)Properties.Resources.ResourceManager.GetObject(resourcename));	0
28417104	28416758	cast a stream or byte array to object	var bf = new BinaryFormatter();\n object ghost = bf.Deserialize(stream);\n return ghost;	0
8204759	7458212	Looping rows of entitydatasource	using (var context = new MyEntities())\n        {\n            string lastSectionHeading = "";\n            bool isFirstHeading = true;\n\n            var dynamicPageItems = context.view_dynamicPageItems;\n            foreach (var item in dynamicPageItems)\n            {\n                if (item.IsActive == 1)\n                {\n                    if (!lastSectionHeading.Equals(item.CategoryId))\n                    {\n                        if (!isFirstHeading)\n                            CloseSection();\n                        lastSectionHeading = item.CategoryId;\n                        AddSettingsSection(item.CategoryDescription);\n                        isFirstHeading = false;\n                    }\n                    AddControl( item.DataType );\n                }\n            }\n        }	0
326011	325788	how to update assemblyBinding section in config file at runtime?	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 == "AssemblyNameToRedirect")\n        {\n            // Put code here to load whatever version of the assembly you actually have\n\n            return Assembly.LoadFrom("RedirectedAssembly.DLL");\n        }\n        else\n        {\n            return null;\n        }\n    };\n}	0
11463634	11463309	EF 5 - The number of primary key values passed must match the number of primary key values defined on the entity	[Column("BudgetItemID")]\n[Key]\npublic int Id { get; set; }	0
12145935	12145911	Is this an example of a semantic violation of encapsulation and if so how do I fix it?	interface IServer \n{\n    ISession Authenticate();\n}\n\ninterface ISession \n{\n    IServer Server{get;}\n    void Post();\n    void Get();\n}	0
16285052	16285021	read a value by its index from a file in C#	double GetValue(int index)\n{   \n   return double.Parse(System.IO.File.ReadAllLines(your file)[0].Split(' ')[index]);\n}	0
30743492	30743383	In c#, how to show specific searched paragraph numbers and docx file name in listview without repeating same file name?	paragph.Clear();\nforeach (string line in lines)\n    {\n        if (line.IndexOf(searchString, StringComparison.OrdinalIgnoreCase) >= 0)\n        {\n            //MessageBox.Show((counter + 1).ToString() + ": " + line);\n            paragph.Add((counter + 1).ToString());\n            arrparagh = paragph.ToArray();\n            toDisplay = string.Join(",", arrparagh);\n            //MessageBox.Show(toDisplay);\n        }\n        counter++;\n    }\n    yield return filePath;	0
7520110	7520080	Linq expression to get all items in a IList where one field is in another List	var filteredProducts = (from p in allProducts\n                            where usersProducts.Contains(p.Id) && p.Type == 1\n                            select p).ToList();	0
9949437	9949010	Getting a null object in wcf service when I am adding a reponse format and body style	{"param1": {"FirstName":"John","LastName":"Doe"}}	0
2291213	2290835	Assigning a version number to a DLL created using CSharpCodeProvider	using System.Reflection;\n[assembly: AssemblyVersion("1.0.0.0")]\n[assembly: AssemblyFileVersion("1.0.0.0")]	0
4525577	4525565	C# Returning an array of a single variable within a class array	int[] Ids = folders.Select(f => f.Id).ToArray();	0
10946683	10939593	One Time Pad chat application with large random keyfiles	byte[] Encrypt(byte[] plain){\n  using (FileStream keyFile = new FileStream(FileName, FileMode.Open))\n  {\n    keyFile.Seek(-plain.Length, SeekOrigin.End);\n    byte[] key = new byte[plain.Length];\n    keyFile.Read(key, 0, plain.Length);    \n    byte[] encrypted = new byte[plain.Length];\n    for(int i=0;i<plain.Length;i++){\n      encrypted[i] = (byte) (plain[i] ^ key[plain.Length - 1 - i]);\n    } \n    keyFile.SetLength(keyFile.Length - plain.Length);   \n    return encrypted;\n  }      \n}	0
771147	771134	Manipulating a thread from a different thread	Thread.Abort	0
4676718	4676698	Setting A Member of Generic Object?	typeof(T).GetProperty(membername).SetValue(obj, o);	0
19821034	19820828	Is LINQ's Enumerable.Take method a good equivalent of SQL's TOP in terms of speed?	var page = query.Take(count)	0
7072945	7071564	WCF Data Services : add two new objects to the database with links between them	service.SaveChanges(SaveChangesOptions.Batch);	0
20554097	20553822	Show specific paragraphs (labels) Using ComboBoxes	switch (comboBox1.SelectedItem.ToString())\n        {\n            case "January":\n                label1.Text = "write something about january...";\n                break;\n            case "February":\n                label1.Text = "write something about February..";\n                break;\n\n            // and so on...\n        }	0
14668515	14668366	Regular Expression Match for Tags	public static bool TryGetTags(string tagsInput, out string[] tags)\n{\n    Regex regex = new Regex(@"^[\w_-]+$");\n\n    tags = tagsInput.Split(',')  // Rule 6\n                    .Select(tag => tag.Trim())\n                    .ToArray();\n\n    if (tags.Last() == "")\n        tags = tags.Take(tags.Length - 1).ToArray();  // Rule 7\n\n    if (tags.Any(tag => tag == ""))  // (no empty tag allowed except last one)\n        return false;\n\n    if (tags.Length > 9)\n        return false;  // Rule 2\n\n    if (tags.Any(tag => tag.Length > 30))\n        return false;  // Rule 4\n\n    if (tags.Distinct().Count() != tags.Length)\n        return false;  // Rule 3\n\n    if (tags.Any(tag => !regex.IsMatch(tag)))\n        return false;  // Rule 5\n\n    return true;\n}	0
29316522	29316504	Entity Framework Filtering with a List of String	from r in db.entries\nwhere filters.contains (r.word.substring(0,1))	0
18054401	18054302	Date format in sql server 2008	VoucherDate.Date.ToShortDateString();	0
33593070	33592846	Get index from array comparing a property of each index in the array	GameObject result = Array.Find(GOArray, g => g.name == "theoneiwant");	0
7484123	7483902	showing camera roll and gallery images in WP7	MediaLibrary.Pictures	0
7837781	7837752	Getting Child page title from user control on Master page	Page.Title	0
8875637	8875584	Get Model from Generic Model	private FileClient CopyFileClientModel(FileClient fileClient) {\n    return this.CopyFileClientModel(fileClient, c => c.Client);\n}\n\nprivate FileContact CopyFileClientModel(FileContact fileContact) {\n    return this.CopyFileClientModel(fileContact, c => c.Client);\n}\n\nprivate TSource CopyFileClientModel<TSource>(TSource fileClientOrContact, Func<TSource, Contact> contactGetter) {\n    var contact = contactGetter(fileClientOrContact);\n    // Whatever else...\n}	0
8393087	8393039	How to call a command of a rad grid	protected void LinkButton1_Click(Object sender, EventArgs   \n {\n         LinkButton button = sender as LinkButton;\n          Apartments apartAdmin = new Apartment();\n           bool deleted = apartAdmin.Delete(int.Parse(button.CommandArgument.ToString()); \n            if (deleted)\n            {\n                radGrid.Rebind();\n            }\n\n }	0
12465272	12464844	Join multiple table and bind into a single Listview using C# .net	borrowedBookList.DataSource =\n    from borrower in Borrowers\n    join transaction in Transactions\n        on borrower.BorrowerID equals transaction.BorrowerID\n    join book in Books\n        on transaction.BookID equals book.BookID\n    select new\n    {\n        borrower.BorrowerID,\n        borrower.BorrowerName,\n        book.BookName,\n        transaction.BorrowDate,\n        transaction.ReturnDate,\n    }\n\nborrowedBookList.DataBind();	0
19457829	19453621	How can I add an InkCanvas element to a Winform?	ElementHost host = new ElementHost();\nInkCanvas ic = new InkCanvas();\nhost.Child = ic;\nControls.Add(host);	0
8015723	8015686	How do I convert this sql to a linq query?	from att in context.Attendees\n                          join webUsers in context.WebUsers\non att.web_user_id equals webUsers.id\n                          join invoice in context.Invoice\n                          on att.InvoiceID equals invoice.ID                          \n                          where invoice.SeminarID == seminarId                                       \n                          select new\n                          {\n                              webUsers.FirstName,\n                              att.InvoiceID                                                       \n                          };	0
10743768	10743729	how can i send a canvas image using vb.net email	Dim data As New Attachment(New MemoryStream(ByteArray), "SomeName")	0
7040319	7040075	Task Parallel Library and Loops	var ii=i;\ntasks[i] = Task.Factory.StartNew(() =>\n                {\n                    nums.Add(numbers[ii]);\n                }, \n                TaskCreationOptions.None);	0
13839710	13587752	How to convert little endian to big and send it over UDP?	int width = sizeof(float);\n\n    int nDataIndex = 0;\n    byte[] data = new byte[myData.Count * width];\n\n        for (int i = 0; i < myData.Count; ++i)\n        {\n            byte[] converted = BitConverter.GetBytes(myData[i]);\n\n            if (BitConverter.IsLittleEndian)\n            {\n                Array.Reverse(converted);\n            }\n\n            for (int j = 0; j < width; ++j)\n            { \n\n                data[nDataIndex+j] = converted[j];          \n            }\n            nDataIndex+=width;\n        }\n\n        client.Send(data, data.Length, remoteEndPoint);	0
5895009	5894949	Access Active Directory data from web application	string username = User.Identity.Name;	0
22109834	21867256	DataGridView auto re-sort	DataGridViewColumn column = dataGridView1.SortedColumn;\nListSortDirection order;\n\nif (dataGridView1.SortOrder.Equals(SortOrder.Ascending))\n   {\n       order = ListSortDirection.Ascending;\n   }\nelse\n   {\n       order = ListSortDirection.Descending;\n   }\n\ndataGridView1.Sort(column, order);	0
31514306	31514188	How to acess page controls inside a static method in ASP.net	public static void Savedata()\n{\n    if (HttpContext.Current != null)\n    {\n        Page page = (Page)HttpContext.Current.Handler;\n        TextBox TextBox1 = (TextBox)page.FindControl("TextBox1");\n\n        TextBox TextBox2 = (TextBox)page.FindControl("TextBox2");\n    }\n}	0
21708829	21694341	FormatExcpetion from Azure Webjobs Host	public static void Function([QueueInput] string testqueue)\n    {\n    }	0
18649584	18644596	Access related member with IL Emit	public Func<bool> GenerateCheckIsLocal() {\n\n            var dynamicMethod = new DynamicMethod("CheckIsLocal", typeof(bool), Type.EmptyTypes, true);\n\n            var il = dynamicMethod.GetILGenerator();\n\n            il.Emit(OpCodes.Call, typeof(HttpContext).GetProperty("Current").GetMethod);\n            il.Emit(OpCodes.Call, typeof(HttpContext).GetProperty("Request").GetMethod);\n            il.Emit(OpCodes.Call, typeof(HttpRequest).GetProperty("IsLocal").GetMethod);\n            il.Emit(OpCodes.Ret);\n\n            return dynamicMethod.CreateDelegate(typeof(Func<bool>)) as Func<bool>;\n        }	0
32659367	32658507	Getting Description from an array of Enums	string findMe = "625 ILCS 5/11-503 - Reckless Driving";\n\nType enumType = typeof(IllinoisNonDisclosureConvictionFormOptions);\nType descriptionAttributeType = typeof(DescriptionAttribute);\n\nforeach (string memberName in Enum.GetNames(enumType))\n{\n    MemberInfo member = enumType.GetMember(memberName).Single();\n\n    string memberDescription = ((DescriptionAttribute)Attribute.GetCustomAttribute(member, descriptionAttributeType)).Description;\n\n    if (findMe.Equals(memberDescription))\n    {\n        Console.WriteLine("Found it!");\n    }\n}	0
10536642	10534158	How to detect if SQL Server CE 4.0 is installed	public bool IsV40Installed()\n    {\n        try\n        {\n            System.Reflection.Assembly.Load("System.Data.SqlServerCe, Version=4.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91");\n        }\n        catch (System.IO.FileNotFoundException)\n        {\n            return false;\n        }\n        try\n        {\n            var factory = System.Data.Common.DbProviderFactories.GetFactory("System.Data.SqlServerCe.4.0");\n        }\n        catch (System.Configuration.ConfigurationException)\n        {\n            return false;\n        }\n        catch (System.ArgumentException)\n        {\n            return false;\n        }\n        return true;\n    }	0
11124974	11124757	How to call a stored proc using a generic DB connection in C#?	//Note the IDisposable interface\npublic class MultiSqlCommand : IDisposable\n{\n  //DbConnectionType  is a custom enum\n  public MultiSqlCommand(DbConnectionType connType, DbConnection conn)\n  {\n    //initialize members\n    ...\n    switch(connType) \n    {\n      case ADO:\n        _cmd = new SqlCommand(_connection);\n        break;\n      case ODBC:\n        ...\n    }\n  }\n\n  //As param name you pass the undecorated parameter name (no @, ?, etc.)\n  public void AddParameter(string strippedName, object value) \n  {\n    //this should be an internal function which gives you an SqlParameter formatted for your specific DbConnectionType\n    object parameter = GetSqlParam(strippedName, value);\n    _cmd.Parameters.Add(object);\n  }\n}	0
9323943	9323822	how to write C# equivalent code corresponding to this XAML code for customizing selected treeviewItem color	var colorBrush = new SolidColorBrush(Colors.Transparent);\ntreeNode.Resources.Add(SystemColors.HighlightBrushKey, colorBrush);	0
1681779	1681715	How can I access the loop index inside a LINQ select?	customers.ToList().ForEach(g => Console.WriteLine("{0} has {1} customers: {2}",\n    g.Country, \n    g.Customers.Count(), \n    string.Join(", ",\n        g.Customers.Select((x, i) => i + ". " + x.CompanyName).ToArray())));	0
17059581	17054636	Fluent Assertions: Compare two numeric collections approximately	source.Should().Equal(target, (left, right) => AreEqualApproximately(left, right, 0.01));	0
15128605	15128426	How to get the .NET framework version that the application is using	string version = Assembly\n                     .GetExecutingAssembly()\n                     .GetReferencedAssemblies()\n                     .Where(x => x.Name == "System.Core").First().Version.ToString();	0
10720606	10720563	How to call a generic overloaded method	public static List<string> GetDocuments(Guid id, string documentType)\n{\n   return GetDocuments<Guid>(id, documentType);\n}	0
448560	448550	C# - Locking issues with Mutex	// if you want timeout support use \n        // try{var success=Monitor.TryEnter(m_syncObj, 2000);}\n        // finally{Monitor.Exit(m_syncObj)}\n        lock(m_syncObj)\n        {\n            l.LogInformation("Got lock to read/write file-based server state.", (Int32)VipEvent.GotStateLock);\n            using (var fileStream = File.Open(ServerState.PATH, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))\n            {\n                // the line below is risky, what will happen if the call to invoke\n                // never returns? \n                result = func.Invoke(fileStream);\n            }\n        }\n\n        l.LogInformation("Released state file lock.", (Int32)VipEvent.ReleasedStateLock);\n        return true;\n\n        // note exceptions may leak out of this method. either handle them here.\n        // or in the calling method. \n        // For example the file access may fail of func.Invoke may fail	0
29161634	29161596	Compare the first letters of a list	var newList = data.Where(s => s.StartsWith(input)).ToList();	0
1588239	1588187	urlauthorization with custom roleprovider	protected void Application_AuthenticateRequest(object sender, EventArgs e)\n{\n    if (HttpContext.Current.User != null)\n    {\n        if (HttpContext.Current.User.Identity.IsAuthenticated)\n        { \n        }\n    }\n}	0
17828179	17812848	Mapping Float with NHibernate	Map(x => x.Factor).Column("FACTOR").CustomSqlType("decimal(p,s)").Not.Nullable();	0
5013796	5013755	how to get the selected items in the checkboxlist control	if (!IsPostBack)	0
10530339	10530303	Execute a Program Which Accept Command Line Parameters	Process.Start("IExplore.exe", "C:\\myPath\\myFile.htm");	0
8191264	8191213	Using System.DateTime in a C# Lambda expression gives an exception	var createdEx = Expression.Lambda<Func<TModel, DateTime?>>...	0
6543178	6543156	How can an ObservableCollection fire a Replace action?	ObservableCollection<string> myCollection = new ObservableCollection<string>;\nmyCollection.Add("One");\nmyCollection.Add("Two");\nmyCollection.Add("Three");\nmyCollection.Add("Four");\nmyCollection.Add("Five");\n\nmyCollection[4] = "Six"; // Replace (i.e. Set)	0
1987429	1987418	ASP.NET Is there a better way to find controls that are within other controls?	public static Control DeepFindControl(Control c, string id)\n{\n   if (c.ID == id)\n   { \n     return c;\n   }\n   if (c.HasControls)\n   {\n      Control temp;\n      foreach (var subcontrol in c.Controls)\n      {\n          temp = DeepFindControl(subcontrol, id);\n          if (temp != null)\n          {\n              return temp; \n          }\n      }\n   }\n   return null;\n}	0
33553755	33553695	How to get full path of a specific assembly?	var location = Path.GetDirectoryName(typeof(YourType).Assembly.Location);	0
12022981	12022637	retrieve the identity value in Linq transaction	System.Data.Common.DbTransaction transaction = null;\n        DBDataContext db = new DBDataContext();\n        db.Connection.Open();\n        transaction = db.Connection.BeginTransaction();\n        db.Transaction = transaction;\n\n        Table1 = new Table1();\n        obj.objName = "some name";\n        db.Table1s.InsertOnSubmit(obj);\n        db.SubmitChanges();\n\n        Table2 obj_info = new Table2();\n        obj_info.Info = "some info";\n        obj_info.Id = obj.Id;\n        db.Table2s.InsertOnSubmit(obj_info);\n        db.SubmitChanges();\n        try\n        {\n            db.SubmitChanges();\n            transaction.Commit();\n        }\n        catch (Exception)\n        {\n            transaction.Rollback();\n        }\n        finally\n        {\n            transaction.Dispose();\n            db.Dispose();\n        }	0
13240729	13240156	Auto-increment dictionary key in c#	public DataPool<T>\n{\n        internal class DataStructHelper<T>\n        {\n            public T DataObject { get; private set; }\n            public int Size { get; private set; }\n            public DataStructHelper(T dataObject)\n            {\n                DataObject = dataObject;\n                Size = GetObjectSize(dataObject);\n            }\n\n            private int GetObjectSize(T TestObject)\n            {\n                BinaryFormatter bf = new BinaryFormatter();\n                using (MemoryStream ms = new MemoryStream())\n                {\n                    byte[] Array;\n                    bf.Serialize(ms, TestObject);\n                    return ms.ToArray().Length;\n                }\n            }\n        }\n    }\n// Other code here\n}	0
18487790	18487720	In C# how to get value from text box using quotes	SqlCommand sqlcmd = sqlcon.CreateCommand();\nsqlcmd.CommandText = "Select distinct transactionName from dbo.tbl " + \n                     "where terminalId = @id";\n\nsqlCmd.Parameters.AddWithValue("@id",  textBox_cardNumber.Text);\n....	0
22569397	22568912	Search contains in a string column for a list of strings using LINQ	List<string> bids = search_string_full_of_comma_bids.Split(';').ToList();\n        query = query.Where(t => bids.Any(b=> \n                               t.BuildingIDs.StartsWith (b+";") //if it's in the start\n                              || t.BuildingIds.EndsWith (";" + b) //end \n                              || t.BuildngIds.Contains(";" + b + ";") //;id;\n                              ));	0
15819676	15819544	Changing App Settings during run time	ConfigurationManager.RefreshSection("appSettings");	0
27906771	27906300	EpiServer: Convert String to XHTMLString	ThankYouMessage  = new XhtmlString("Default thank you message")	0
26350899	26350580	How to read a CSV file into a int[] C#	using (var sr = new StreamReader("a.csv"))\n{\n    var myArray = sr.ReadToEnd()\n        .Split('\n')\n        .SelectMany(s => s.Split(',')\n            .Select(x => int.Parse(x)))\n        .ToArray<int>();\n\n    foreach(var x in myArray)\n        Console.WriteLine (x);\n}	0
8379966	8379707	Reading a file and mapping values	using (var sr = File.OpenText(path))\n{\n  var line = string.Empty;\n  while ((line = sr.ReadLine()) != null)\n  {\n    var dataPoints = line.Split(',');\n    // Create Your Data Mappings Here\n    // dataPoints[0]...\n  }\n}	0
7320703	7320608	Simple way to compare Dates in DateTime attribute using Entity Framework 4 and Linq queries	var newAuctionsResults = repo.FindAllAuctions()\n                        .Where(a => a.IsActive == true \n                                    || (a.StartTime.Value.Year == todayYear\n                                        && a.StartTime.Value.Month == todayMonth\n                                        && a.StartTime.Value.Day == todayDay))\n                        .ToList();	0
11258283	11257212	Parse JSON with newtonsoft	WebClient wc = new WebClient();\nvar json = (JObject)JsonConvert.DeserializeObject(wc.DownloadString(url));\n\nvar country = json["results"]\n                .SelectMany(x => x["address_components"])\n                .FirstOrDefault(t => t["types"].First().ToString() == "country");\n\nvar name = country!=null ? country["long_name"].ToString() : "";	0
1114396	1114363	C# How to write one byte at an offset?	Stream outStream = File.Open(filename, FileMode.Open);\noutStream.Seek(0x6354C, SeekOrigin.Begin);\noutStream.WriteByte(0xb0);	0
5838270	5838252	Fluent NHibernate - 'failed to lazily initialize a collection' - Querying Over a Collection	Json(results)	0
6219932	6219614	Convert a long to two int for the purpose of reconstruction	static int[] long2doubleInt(long a) {\n        int a1 = (int)(a & uint.MaxValue);\n        int a2 = (int)(a >> 32);\n        return new int[] { a1, a2 };\n    }\n\n    static long doubleInt2long(int a1, int a2)\n    {\n        long b = a2;\n        b = b << 32;\n        b = b | (uint)a1;\n        return b;\n    }\n\n\n    static void Main(string[] args)\n    {\n        long a = 12345678910111213;\n        int[] al = long2doubleInt(a);\n        long ap = doubleInt2long(al[0],al[1]);\n        System.Console.WriteLine(ap);\n        System.Console.ReadKey();\n    }	0
856103	856086	is it possible to add a list to a structure?	struct MyStruct\n{\n    public List<string> MyList;\n    public int MyInt;\n\n    public MyStruct(int myInt)\n    {\n        MyInt = myInt;\n        MyList = new List<string>();\n    }\n}	0
18090081	18090031	Clean up img tags in a full html string	var doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nforeach (var img in doc.DocumentNode.Descendants("img"))\n{\n    img.Attributes.Remove("width");\n    img.Attributes.Remove("height");\n}\n\nvar newhtml = doc.DocumentNode.OuterHtml;	0
34423426	34423338	What would be a better way to filter out non-hexadecimal characters from a string?	public bool OnlyHexInString(string test)\n{\n    // For C-style hex notation (0xFF) you can use @"\A\b(0[xX])?[0-9a-fA-F]+\b\Z"\n    return System.Text.RegularExpressions.Regex.IsMatch(test, @"\A\b[0-9a-fA-F]+\b\Z");\n}	0
12041503	12031730	How to load image from isolated storage for secondary tile	string imageFolder = @"\Shared\ShellContent"; \nstring shareJPEG = "shareImage.jpg"; \n\n...\n\nprivate void CreateLiveTile(TileItem item)  \n{   \n    var title = item.Title.ToString();  \n    string tileParameter = "Param=" + item.Title.ToString();  \n\n    ShellTile Tile = CheckIfTileExist(tileParameter);  // Check if Tile's title has been used               \n\n    if (Tile == null)  \n    {        \n        string filePath = System.IO.Path.Combine(imageFolder, shareJPEG);                \n        background = new Uri(@"isostore" + filePath, UriKind.Absolute);    //this worked\n\n        ...\n\n     }\n}	0
3987940	3987846	How to create value generator ala hex in c#	public class UniqueKeyMaker\n{\n    private int[] keys = new int[8];\n\n    public void Reset()\n    {\n        for (int i = 0; i < keys.Length; i++)\n            keys[i] = 0;\n    }\n\n    public string NextKey()\n    {       \n        string key = getCurrentKey();\n        increment();\n        return key;\n    }\n\n    private void increment()\n    {\n        int i = 7;\n        while (keys[i] == 35)\n        {\n            keys[i] = 0;\n            i--;\n        }\n\n        keys[i]++;\n    }\n\n    private string getCurrentKey()\n    {\n        StringBuilder sb = new StringBuilder();\n        for (int i = 0; i < 8; i++)\n        {\n            if (keys[i] < 10)\n                sb.Append((char)(keys[i] + (int)'0'));\n            else\n                sb.Append((char)(keys[i] - 10 + (int)'a'));\n        }\n        return sb.ToString();\n    }\n}	0
9650348	9650318	Mapping Model Properties into Controller	public class HomeController\n{\n   public ActionResult Index()\n   {\n      // Do something with model here, in this example we are creating a new model\n      var model = new Model(); \n\n      // Send the model to the view, this is then available as @Model\n      return View(model);\n   }\n}	0
2861353	2861285	How to create function which lets you choose one of 3 parameters values?	public enum DataFormat{ JSON=0, XML=1, PRINTR=2 } \n\npublic ReturnType SomeFunction( DataFormat format )\n{\n    if( DataFormat.JSON == format ) \n        return ....\n    //etc\n}	0
15107469	15107448	Create string in MessageBox or WriteLine	string s = string.Empty;\nMessageBox.Show(s = string.Format("Hello World"));	0
9216287	9215772	Creating an XML from tiered class structure	armyListing.army.Add(army)	0
6569765	6558616	Developing SharePoint custom web part. How to render lookup field?	spfieldlookupvalue value=new SpFiledlookupvalue(item["column name"]);\nstring id=value.lookupid;//you can retrieve the text,id\nstring text=value.lookuptext;	0
20532865	20532700	String.Format with null values C#	string[] data = new[] { \n    postalAddress.Line1, \n    postalAddress.Line2, \n    postalAddress.Line3, \n    postalAddress.Line4, \n    postalAddress.Suburb, \n    postalAddress.StateCode, \n    postalAddress.Pcode \n};\n\nstring address = string.Join(", ", \n                             data.Where(e => !string.IsNullOrWhiteSpace(e));	0
3169331	3161359	Can I render html from ASP.NET Page objects outside ASP.NET applications?	static public string GetHTML(Control myControl)\n{\n        System.IO.StringWriter sw = new System.IO.StringWriter();\n        HtmlTextWriter myWriter = new HtmlTextWriter(sw);\n        myControl.RenderControl(myWriter);\n        return sw.ToString();\n}	0
15630491	15628496	How to suppress the subreport when subreport dataset value has a status of "false"	IF {db_column} = 1 THEN false ELSE true	0
3406197	3406169	C#: Converting byte[] to UTF8 encoded string	string yourText = Encoding.UTF8.GetString(yourByteArray);	0
28712190	28712111	How to concatenate two values into text box in c#?	string time = "00";\nint Result = 02;\ntextresult.Text=Result.ToString("D2") + ":" + time;	0
29972692	29972600	how to set column in center position	listView1.Columns.Add("x", 100, HorizontalAlignment.Center)	0
19411944	19410295	How to query multiple DbSets in a single LINQ statement	var products = context.Products\n    .Where(p =>\n        p.Name == "searchString" ||\n        p.OrderDetailList.Any(od => od.Order.orderName == "searchString"))\n    .ToList();	0
33848621	33847052	How to make textbox accept only currency format input?	private void textBox1_TextChanged(object sender, EventArgs e)\n    {\n        textBox1.Text = string.Format("{0:#,##0.00}", double.Parse(textBox1.Text));\n    }\n\n    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)\n    {\n        if (!char.IsControl(e.KeyChar) && !char.IsDigit(e.KeyChar) && (e.KeyChar != '.'))\n        {\n            e.Handled = true;\n        }\n\n        // only allow one decimal point\n        if ((e.KeyChar == '.') && ((sender as TextBox).Text.IndexOf('.') > -1))\n        {\n            e.Handled = true;\n        }\n    }	0
13748961	13748827	how to call and execute MySQL commands programmatically?	string binary = @"C:\MySQL\MySQL Server 5.0\bin\mysqldump.exe"\nstring arguments = @"-uroot -ppassword sample"\nProcessStartInfo PSI = new System.Diagnostics.ProcessStartInfo(binary, arguments);\nPSI.RedirectStandardInput = true;\nPSI.RedirectStandardOutput = true;\nPSI.RedirectStandardError = true;\nPSI.UseShellExecute = false;\nProcess p = System.Diagnostics.Process.Start(PSI);\nEncoding encoding = p.StandardOutput.CurrentEncoding;\nSystem.IO.StreamWriter SW = new StreamWriter(@"c:\backup.sql", false, encoding);\np.WaitOnExit();\nstring output = p.StandardOutput.ReadToEnd()\nSW.Write(output)\nSW.Close();	0
13732549	13732495	Regex: C# extract questions within a text	. , ; ? !	0
25886045	25885717	How to inject MessageHeaders into WCF calls	using (OperationContextScope scope = new OperationContextScope(((IContextChannel) proxy))\n  {\n          // your code to add custom header\n  }	0
7561182	7561123	Emailing the contents of a Textbox with Outlook	oMsg.Body = TextBox1.text;	0
2403864	2403844	Using Linq to select a range of members in a list	int[] ia = new int[] { -4, 10, 11, 12, 13, -1, 9, 8, 7, 6, 5, 4, -2, \n                        6, 15, 32, -5, 6, 19, 22 };\n\nvar result = ia\n             .SkipWhile(i => i != -1)\n             .Skip(1)\n             .TakeWhile(i => i >= 0);	0
21138733	21138641	Add one in Viewsate on click	ViewState["questionNumberCounter"]=Convert.ToInt32(ViewState["questionNumberCounter"])+1	0
9994374	9993372	get response from aspx page in json format instead of plain html	protected override void Render(HtmlTextWriter writer)\n    {\n        var sw = new System.IO.StringWriter();\n        var tw = new HtmlTextWriter(sw);\n        base.Render(tw);\n\n        Response.Write(String.Format("{{\"myresponse\": {{  \"id": \"123",\"html\":\"{0}\"}}}}"\n        , Server.HtmlEncode(sw.ToString()).Replace("\n"," "));\n        Response.Flush();\n        Response.End();\n    }	0
7621571	7621464	Can not convert a row to a DataTable in C#	foreach (DataRow row in dt.Rows)\n{\n    try\n    {\n        DataTable newtable = new DataTable();\n        newtable = dt.Clone(); // Use Clone method to copy the table structure (Schema).\n        newtable.ImportRow(row); // Use the ImportRow method to copy from dt table to its clone.\n        UserInfo = GetInfo(newtable);\n\n    catch (Exception exep)\n    {\n        //\n    }\n}	0
12005060	12004350	Size limitation when using a texture as a render target	Surface oldDepthBuffer = device.DepthStencilSurface;\nTexture db = new Texture(device, w, w, 1, Usage.DepthStencil, oldDepthBuffer.Description.Format, Pool.Default);\n\nSurface myDepthBuffer = db.GetSurfaceLevel(0);\n\ndevice.SetRenderTarget(0, surface);\ndevice.DepthStencilSurface = myDepthBuffer;\n\n// RENDER to texture\n\ndevice.DepthStencilSurface = oldDepthBuffer;	0
18835609	18831497	Apply file filters to string [] of filenames , without opening OpenFileDialog	static string[] GetFiles(string directory, params string[] extensions)\n{\n    var allowed = new HashSet<string>(extensions, StringComparer.CurrentCultureIgnoreCase);\n\n    return Directory.GetFiles(directory)\n                    .Where(f => allowed.Contains(Path.GetExtension(f)))\n                    .ToArray();\n}\n\nstatic void Main(string[] args)\n{\n    string[] files = GetFiles(@"D:\My Documents", ".TXT", ".docx");\n    foreach(var file in files)\n    {\n        Console.WriteLine(file);\n    }\n}	0
28663590	28621421	How To Set Folder Permissions in Elastic Beanstalk Using YAML File?	{\n    "container_commands": {\n        "01": {\n            "command": "icacls \"C:/inetpub/wwwroot/AppName_deploy/App_Data/AppFolder\" /grant DefaultAppPool:(OI)(CI)F"\n        }\n    }\n}	0
16669372	16669345	how i can use a string that have the same structure how a xml file for a treeview?	private void BuildTree(TreeView treeView, XDocument doc)\n    {\n        TreeNode treeNode = new TreeNode(doc.Root.Name.LocalName);\n        treeView.Nodes.Add(treeNode);\n        BuildNodes(treeNode, doc.Root);\n    }\n\n    private void BuildNodes(TreeNode treeNode, XElement element)\n    {\n        foreach (XNode child in element.Nodes())\n        {\n            switch (child.NodeType)\n            {\n                case XmlNodeType.Element:\n                    XElement childElement = child as XElement;\n                    TreeNode childTreeNode = new TreeNode(childElement.Name.LocalName);\n                    treeNode.Nodes.Add(childTreeNode);\n                    BuildNodes(childTreeNode, childElement);\n                    break;\n                case XmlNodeType.Text:\n                    XText childText = child as XText;\n                    treeNode.Nodes.Add(new TreeNode(childText.Value));\n                    break;\n            }\n        }\n    }\n}	0
21364302	21363747	Change HTTP headers Selenium + PhantomJS	PhantomJSOptions options = new PhantomJSOptions();\noptions.AddAdditionalCapability("phantomjs.page.settings.userAgent", "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:26.0) Gecko/20100101 Firefox/26.0");\nIWebDriver driver = new PhantomJSDriver(options);	0
3355534	3355407	Validate string is base64 format using RegEx?	private static readonly HashSet<char> _base64Characters = new HashSet<char>() { \n    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', \n    'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'a', 'b', 'c', 'd', 'e', 'f', \n    'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', \n    'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '+', '/', \n    '='\n};\n\npublic static bool IsBase64String(string value)\n{\n    if (string.IsNullOrEmpty(value))\n    {\n        return false;\n    }\n    else if (value.Any(c => !_base64Characters.Contains(c)))\n    {\n        return false;\n    }\n\n    try\n    {\n        Convert.FromBase64String(value);\n        return true;\n    }\n    catch (FormatException)\n    {\n        return false;\n    }\n}	0
29193064	29192919	Getting data from the sqlite db into c# string	var ordinal = reader.GetOrdinal("kyrname");\nwhile (reader.Read())\n    {\n        result[i] = reader.GetString(ordinal);\n        i++;\n    }	0
33827251	33824396	Separate multiple categorized tests	[Test]\n[Category("Category1")\nprivate void DoSomethingForCat1()\n{\n    TestSomeStuff("category1");\n}\n\n[Test]\n[Category("Category2")\nprivate void DoSomethingForCat2()\n{\n    TestSomeStuff("category2");\n}\n\n\nprivate void TestSomeStuff(string category)\n{\n    if(category == "Category1"){\n        (...)\n    }\n    else if(category == "Category2"){\n        (...)\n    }\n}	0
9326850	9326777	How to call a function written in VB from C# application	objectname.abc(3,"SomeSting");	0
8382959	8381728	ASP.NET DataTable based GridView Header Filter	DataRow[] rows = dTable.Select(" user_tb > 5"); // default\nDataRow[] rows1 = dTable.Select(" user_tb > 5", "user_tb ASC"); // with sorting	0
28189013	28187521	How can I force a C# FtpWebRequest to use a direct IP to get onto the Internet instead of going through an HTTP proxy?	127.0.0.1       localhost	0
23551826	23551258	Create LI from C# code behind into an ASPX page	cblTest.DataSource = "YourDataTableOrDataset";\n        cblTest.DataValueField = "YourIDColumnFromYourTable";\n        cblTest.DataTextField = "YourColumnName";\n        cblTest.RepeatDirection = RepeatDirection.Horizontal;//Option of vertical\n        cblTest.RepeatColumns = 5; //or however many you need i.e how many columns you want to go across before repeating\n        cblTest.CssClass = "YourCSSClass"; //for styling the checkboxlist\n        cblTest.DataBind();	0
4748078	4748045	C# Array or other data structure	Dictionary<int, int> data = new Dictionary<int, int>();\ndata.Add(1,1);\ndata.Add(2,2);\ndata.Add(5,5);\ndata.Add(6,4);	0
1481153	1481139	iTextSharp table width 100% of page	table.Width = 100;	0
26964783	26964750	C# setter/getter of two variables	public int var1 { get;set;}\n\npublic int var2 { get;set;}	0
33180000	33150369	How to change the texture of object at run time on button click in unity by using AR camera	transform.GetComponent<Renderer>().material.texture="yourTexture"	0
6255667	3607442	Forcing a (generic) value type to be a reference	struct Example<T>\n{\n    private object obj;\n    public T Obj\n    {\n        get\n        {\n            return (T)obj;\n        }\n        set\n        {\n            this.obj = value;\n        }\n    }\n}	0
10108699	10108565	Changing SqlConnection timeout	command.CommandTimeout = 60; //The time in seconds to wait for the command to execute. The default is 30 seconds.	0
30481481	30461745	Regex remove all numerics and dots with empty strings	Addresses.FirstOrDefault(x => x.paon.Trim() == Regex.Replace(exception.AddressLineOne, "[^0-9]", "") && x.thorofare.Trim() == (Regex.Replace(exception.AddressLineOne, "[^a-zA-Z\\s]", "").Trim()))	0
2220086	2220052	Retrieving data from Stored Procedure which is not in a ROW [ASP.NET C#]	using(SqlConnection conn = new SqlConnection("YOUR_CONNECTION_STRING"))\n{\n    conn.Open();\n    using (SqlCommand command = conn.CreateCommand())\n    {\n        command.CommandType = CommandType.StoredProcedure;\n\n        SqlParameter parameter = command.Parameters.Add("@yourParameter", SqlDbType.VarChar, 50);\n        parameter.Direction = ParameterDirection.Output;\n\n        command.CommandText = "YOUR_STORED_PROCEDURE";\n        command.ExecuteNonQuery();\n        return parameter.Value;    \n    }\n}	0
1344083	1344025	How to make a class Thread Safe	public class SharedLogger : ILogger\n{\n   public static SharedLogger Instance = new SharedLogger();\n\n   public void Write(string s)\n   {\n      lock (_lock)\n      {\n         _writer.Write(s);\n      }\n   }\n\n   private SharedLogger() \n   { \n      _writer = new LogWriter();\n   }\n\n   private object _lock;\n   private LogWriter _writer;\n}	0
3737605	3737307	nHibernate Select statement for specific fields	var specificFields = db.Session.CreateQuery("SELECT t.Name, t.Address FROM MyTable t WHERE t.Name='AName'").List();\n\nvar specificFields = db.Session.CreateQuery("SELECT t.Name, t.Address FROM MyTable t WHERE t.Name='AName'").List<Tuple<string,string>>();	0
10827085	10826994	Splitting an array using LINQ	var batchSize = 3;\nvar batched = orig\n    .Select((Value, Index) => new {Value, Index})\n    .GroupBy(p => p.Index/batchSize)\n    .Select(g => g.Select(p => p.Value).ToList());	0
25903087	25903037	get last data from looping in c#	var lastRow = splitRow.Last();\n        var lastPosition = lastRow.Split(';').First();	0
13106530	13106493	How do I only allow number input into my C# Console Application?	string _val = "";\nConsole.Write("Enter your value: ");\nConsoleKeyInfo key;\n\ndo\n{\n    key = Console.ReadKey(true);\n    if (key.Key != ConsoleKey.Backspace)\n    {\n        double val = 0;\n        bool _x = double.TryParse(key.KeyChar.ToString(), out val);\n        if (_x)\n        {\n            _val += key.KeyChar;\n            Console.Write(key.KeyChar);\n        }\n    }\n    else\n    {\n        if (key.Key == ConsoleKey.Backspace && _val.Length > 0)\n        {\n            _val = _val.Substring(0, (_val.Length - 1));\n            Console.Write("\b \b");\n        }\n    }\n}\n// Stops Receving Keys Once Enter is Pressed\nwhile (key.Key != ConsoleKey.Enter);\n\nConsole.WriteLine();\nConsole.WriteLine("The Value You entered is : " + _val);\nConsole.ReadKey();	0
12930788	12927118	mocking a method with an anonymous type argument	public class Estandar {\n    public int Id { get; set; }\n}\n\npublic interface IConector {\n    IEnumerable<Estandar> listar(string name, Estandar estandar, object key);   \n}\n\n\n[TestMethod]\npublic void CheckAnonymous() {\n\n    var connector = new Mock<IConector>();\n\n    connector.Setup(cn => cn.listar("FetchEstandar",\n                                    It.IsAny<Estandar>(),\n                                    It.Is<object>(it => MatchKey(it, 1))))\n             .Returns(new List<Estandar> { new Estandar { Id = 1 } });\n\n    var entidad = connector.Object.listar("FetchEstandar", new Estandar(), new { Id = 1 });\n\n    Assert.AreEqual(1, entidad.Count());\n\n}\n\npublic static bool MatchKey(object key, int soughtId) {\n    var ret = false;\n    var prop = key.GetType().GetProperty("Id");\n    if (prop != null) {\n        var id = (int)prop.GetValue(key, null);\n        ret = id == soughtId;\n    }\n    return  ret;\n}	0
27717037	27716583	How to extract "Message" part from Google API error message	string message1 = "Google.Apis.Requests.RequestError.Entity already exists. "\n                          +"[409]. Errors [. Message[Entity already exists.] Location [ - ] Reason [duplicate] Domain [global] .]";\n        string message2 = "Google.Apis.Requests.RequestError.Domain user limit reached. "\n                          +"[412]. Errors [. Message[Domain user limit reached.] Location [If-Match - header] Reason[limitExceeded] Domain[global] .]";\n\n        string pattern = @"Message\[((\w+\s){2,}(\w+\s?)*)\.\]";\n\n        Regex regex = new Regex(pattern);\n\n        Match m = regex.Match(message1); //or regex.Match(message2)\n        if (m.Success)\n        {\n            Group g = m.Groups[1]; //m.Groups[0] will Match 'Message[.....]'\n            CaptureCollection cc = g.Captures;\n\n            for (int i = 0; i < cc.Count; i++)\n            {\n                Capture c = cc[i];\n                Console.WriteLine("Message: {0}", c);\n            }\n        }\n\n        Console.ReadLine();	0
1989418	1989342	Convert string to datetime Using C#	var userdateformat = DateTime.ParseExact("20101020", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);	0
7459301	7459272	How can I use linq to go from an array of indices to a collection of objects?	int[] indices = { 0, 2, 4, 9, 10, 11, 13 };\nstring[] strings = { "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m", "n", "o", "p", "q" };\n\nIEnumerable<string> results = indices.Select(s => strings[s]);\n\n// or List<string> results = indices.Select(s => strings[s]).ToList();\n\nforeach (string result in results) // display results\n{\n    Console.WriteLine(result);\n}	0
17066519	17066417	Deserializing a JSON String into a custom Java Object	final ObjectMapper mapper = new ObjectMapper();\n\nfinal AmazonSNSMessage message \n    = mapper.readValue(yourInput, AmazonSNSMessage.class);	0
11696259	11695784	binding each item on gridview row	CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type GridViewRowPresenter}}, Path=DataContext}"	0
33020383	33020329	Basic C# Console Application Error	Console.ReadLine();\n}	0
21392671	21392623	C# 2D array size defined by user input, however need user input to populate also?	for (int i = 0; i < row; i++)\n{\n        for (int j = 0; j < column; j++)\n        {\n            Console.Write("Enter a number: ");\n            var value = Console.ReadLine();\n            int result; \n            if(int.TryParse(value,out result)) arrayFour[i,j] = result;\n            else \n            {\n               Console.WriteLine("Invalid value! try again..");\n               j--;\n            }\n        }\n\n}	0
1180360	1178399	How do I create a Null Object in C#	public class Animal {\nprotected Animal() { }\n\npublic Animal(string name, string species) {\n_Name = name;\n_Species = species;\n}\n\npublic virtual string Name {\nget { return _Name; }\nset { _Name = value; }\n}\nprivate string _Name;\n\npublic virtual string Species {\nget { return _Species; }\nset { _Species = value; }\n}\nprivate string _Species;\n}\n\npublic sealed class NullAnimal : Animal {\npublic override string Name {\nget { return String.Empty; }\nset { }\n}\npublic override string Species {\nget { return String.Empty; }\nset { }\n}\n}	0
17865718	17865473	What is the best data structure for dynamically populating a dropdown menu?	public class MenuItem\n{\n   public string Text { get; set; }\n   public string NavigateUrl { get; set; }\n   .\n   .\n\n   public List<MenuItem> Children { get; set; }\n\n}	0
15735824	15694783	MySqlCommand Prepare() never sets IsPrepared to true	MySqlConnectionStringBuilder connBuilder = new MySqlConnectionStringBuilder();\n// .. set up the rest of your connection\nconnBuilder.IgnorePrepare = false;\n\nMySqlConnection conn = new MySqlConnection(connBuilder.ToString());	0
7755336	6446313	how to test hovering in WatiN	Browser _currentBrowser = new IE();\n\nLink myLink = _currentBrowser.Link(Find.ById("navigation-id"));\nmyLink.FireEvent("mouseover");\nmyLink.FireEvent("mousemove");	0
20009215	20008199	How to make this Reflection work with WinRT	var currentAssembly = GetType().GetTypeInfo().Assembly;\nvar migrations = currentAssembly.DefinedTypes\n                                .Where( type => type.ImplementedInterfaces\n                                                    .Any(inter => inter == typeof (IMigration)) && !type.IsAbstract )\n                                .OrderBy( type => type.Name );	0
6036200	6036034	Shows timer (minutes and seconds) in console	Stopwatch sw = new Stopwatch();\nsw.Start();\n\nwhile (true)\n{\n    Console.SetCursorPosition(0, 0);\n    Console.Write(sw.Elapsed.ToString("g"));\n\n    if (sw.Elapsed.TotalMinutes > 30)\n        break;\n}	0
12818012	12817911	Implementing an interface with a generic constraint	public class Class1<T> : IInterface\nwhere T : Test2\n{\n    public T Test { get; private set; }\n\n    Test2 IInterface.Test\n    {\n        get { ... }\n    }\n}	0
28031906	28031442	JSON parsing in C#	var reader = new StreamReader(Request.InputStream);\nvar json = reader.ReadToEnd();\ncmupdate u = JsonConvert.DeserializeObject<cmupdate>(json);\n\nstring output = "";\noutput = "ListID: " + u.ListID;\nList<Event> t = u.Events;\noutput += "OldEmailAddress:" + t[0].OldEmailAddress + " EmailAddress:" + t[0].EmailAddress;	0
25492687	25492608	VB.NET Creating a dynamic StripMenu	fileitem.DropDownItems.Add("New", _\n                           Image.FromFile("C:\\add.png"), _\n                           AddressOf NewFile_click)	0
19385516	19384873	Accessing a WebService using a C# Script	using Company.WebServices;\n\nnamespace ST_abcdef.csproj\n{\n    [System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]\n    public partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase\n    {\n        public void Main()\n        {\n            WebService1 webService1 = new WebService1();\n            var result = webService1.methodA("param1", "param2");\n            // process result\n        }\n    }\n}	0
13442324	13442119	extracting values of text from html source file	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(html);\n\nvar table = doc.DocumentNode.SelectNodes("//table/tr")\n               .Select(tr => tr.Elements("td").Select(td => td.InnerText).ToList())\n               .ToList();	0
30945069	30944913	Return Variable From Method	private static int runupdates(string arr)\n{\n    updatestatement = "";\n    using (SqlConnection connection = new SqlConnection(SQLConnectionString))\n    {\n        connection.Open();\n        using (SqlCommand command = new SqlCommand(updatestatement, connection))\n        {\n        command.CommandText = updatestatement;\n        int nummmm = command.ExecuteNonQuery();\n        connection.Close();\n        }\n    }\n    return nummmm;\n}	0
26627610	26627364	Scrape Data and join fields from web in c#	listBox1.DataSource = programasSPTV1.Zip(horasSPTV1, (a,b) => (a + " : " + b)).ToList();	0
30829296	30822310	c#: strange shift in data buffer during communication with device	int cnt = 0;\nwhile (cnt < 2) cnt += port.Read(size, cnt, 2 - cnt);	0
6155580	6155381	How to use INotifyPropertyChanged on a property in a class within a class..?	public class YourViewModel \n{\n    public YourViewModel()\n    {\n        AspectRatio.PropertyChanged += AspectRatio_PropertyChanged;\n    }\n\n    void AspectRatio_PropertyChanged(object sender, PropertyChangedEventArgs e)\n    {\n        if (e.PropertyName == "Value")\n            NotifyPropertyChanged("ResolutionList");\n    }        \n}	0
1289802	1289756	Most elegant way to query XML string using XPath	XDocument doc = XDocument.Parse(someStringContainingXml);\nvar cats = from node in doc.Descendants("Animal")\n           where node.Attribute("Species").Value == "Cat"\n           select node.Attribute("Name").Value;	0
22956846	22929568	Unable to Bind List Box in Windows Phone 7 after consuming xml web service	public class Prices\n{\n    public string category { get; set; }\n    public string price { get; set; }\n}	0
969805	969796	How to skip a record in a Foreach	foreach (var PharosUserItem in ListRef)\n    {\n        ADUser User;\n        try\n        {\n            User = new ADUser(PharosUserItem.UserLoginPharos);\n        }\n        catch (ByTel.DirectoryServices.Exceptions.UserNotFoundException ex)\n        {\n            continue;\n        }\n    }	0
10514638	10514530	How can we access a binary from GAC irrespective of .Net Framework	Assembly.Load("SampleAssembly, Version=1.0.2004.0, Culture=neutral, PublicKeyToken=8744b20f8da049e3");	0
3076085	3076036	Converting the children of XElement to string	var result = string.Concat(element.Nodes());	0
4344855	4344835	can't start winForm from a thread	Message Loop	0
2860619	2860578	WPF DataContext syntax - Convert from C# to VB	Private Sub Button_Click(ByVal sender As System.Object, ByVal e as RoutedEventArgs) Handles Button.Click\n DirectCast(DataContext, Person).FirstName = "blah blah"\nEnd Sub	0
21339751	21339627	C# equivalent of vbnet interface implementations	class WebServiceClass : Interface1, Interface2\n{\n  public string Method1(int result) { ... }\n  public void Method2(long id, int p3) { ... } \n  public void Method3(long in) { ... } \n\n  string Interface1.Method1(int result) { return Method1(result); }\n  void Interface1.Method2(long id, int p3) { Method2(id, p3); }\n  string Interface2.Method1(int result) { return Method1(result); } \n  void Interface2.Method2(long in) { Method3(in); }\n}	0
29309955	29309266	Issue to properly cast an event including a customized EventArgs	private void B_Say_Click(object sender, EventArgs e) {\n    var customArgs = e as Custom_EventArgs;\n    if (null != customArgs) {\n        // do what you want\n    }\n}	0
12035436	12034858	ASCII Values For Keyboard Key Press Events?	System.Convert.ToUInt16('7')	0
31533257	31532851	Adding columns to Datagrid	DetailsDlg.Columns[0].Header = "New column name";	0
22110525	22110435	Need help fixing a lambda join C#	var CategoryItems =\nfrom item in db.Items\njoin rental in db.Rentals on item.itemID equals rental.ItemID\nwhere item.CategoryID == CategoryID && rental.RentedBy == 0\norderby item.ListDate descending\nselect new DisplayItem \n{  \n    AvailableForPurchase = item.AvailableForPurchase,\n    ...\n};	0
14806122	14726146	Scrolling list view when another list view is scrolled	class SyncListView: ListView\n{\n    public SyncListView()\n    {\n    }\n\n    public Control Buddy { get; set; }\n\n    private static bool scrolling;   // In case buddy tries to scroll us\n\n    protected override void WndProc(ref Message m) \n    {\n    base.WndProc(ref m);\n    // Trap WM_VSCROLL message and pass to buddy\n    if ((m.Msg == 0x115 || m.Msg == 0x20a) && !scrolling && Buddy != null && Buddy.IsHandleCreated)\n    {\n        scrolling = true;\n        SendMessage(Buddy.Handle, m.Msg, m.WParam, m.LParam);\n        scrolling = false;\n    }\n}\n\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    private static extern IntPtr SendMessage(IntPtr hWnd, int msg, IntPtr wp, IntPtr lp);\n\n}	0
3032546	3032528	How do I include a hyphen in a hyperlink Regex?	Regex("((http://|www\\.)([A-Z0-9.\-:]{1,})\\.[0-9A-Z?;~&#=\\-_\\./]{2,})", RegexOptions.Compiled | RegexOptions.IgnoreCase);	0
25239273	25238057	Saving textbox text into XML file	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!Page.IsPostBack)\n    {\n        PutWhatWasBefore();\n    }\n}	0
3588267	3586794	How to find object in nHibernate/castle activerecord session	ISession.Contains()	0
16413447	16409157	change default origin from top-left to center in XNA	public class Sprite\n{\n    static Vector2 WorldOrigo = new Vector2(400, 240); //center of a 800x480 screen\n\n    Texture2D Texture { get; set; }\n    Vector2 Origin { get; set; }\n\n    public Sprite(Texture2D texture)\n    {\n        Texture = texture;\n        Origin = new Vector2(texture.Width / 2, texture.Height / 2);\n    }\n\n    public void Draw(Vector2 position, SpriteBatch spriteBatch)\n    {\n        spriteBatch.Draw(Texture, WorldOrigo + position - Origin, Color.White);\n    }\n}	0
10695548	10695186	Parsing Image Path in ImageResizer	var sitePath = MapPath(@"~");\nvar relativePath= i.FinalPath.Replace(sitePath, "~");	0
13103644	12992153	Get generic collection values from DataGridView to Xml file	List<Test>laneConfigs = new List<Test>();//From a class\n            foreach (DataGridViewRow dr in dataGridView1.Rows)\n            {\n                int bbbBorder = 0;\n                Int32.TryParse(dr.Cells["BBor"].Value.ToString(), out bbbBorder );\n                int eeee= 0;\n                Int32.TryParse(dr.Cells["EBor"].Value.ToString(), out eee);\n\n                LaneConfig laneConfig = new LaneConfig(\n                    dr.Cells["ID"].Value.ToString(),\n                    (TrafficLaneType)Enum.Parse(typeof(TrafficLaneType), dr.Cells["Type"].Value.ToString()),\n                    new ValueWithUnit<int>(bbbBorder, "mm"),\n                    new ValueWithUnit<int>(eee, "mm"));\n\n                laneConfigs.Add(llaneConfig);\n            }	0
22264578	22213831	Get value from a dictionary created from a PropertyInfo.GetValue	dynamic wrkCacheTableObject = wrkTablePropInfo.GetValue(wrkGSD, null);\n//--- get the row using dynamic\ndynamic wrkRow = wrkCacheTableObject[(long)varAJR.rowID];\n//--- put the row back\nwrkCacheTableObject[(long)varAJR.rowID]= wrkRow;	0
15983593	15983520	Decrypt encryption done with RsaProtectedConfigurationProvider in web.config file outside of ASP.NET	string section = "connectionStrings";\n\nConfiguration config = WebConfigurationManager.OpenWebConfiguration(Request.ApplicationPath);\nConfigurationSection configSection = config.GetSection(section);\n\nif (configSection.SectionInformation.IsProtected)\n{\n     configSect.SectionInformation.UnprotectSection();\n     config.Save();\n}	0
10531516	10531458	LINQ, Filtering out attachments with mappings	var filterdFiles = files\n                   .Where(x=> \n                          mappings.Any(m=>x.filename.contains(m.Value)))	0
8642979	8642808	disposing generic list of bitmapimages	private BitmapImage LoadImage(string myImageFile)\n        {\n            BitmapImage myRetVal = null;\n            if (myImageFile != null)\n            {\n                BitmapImage image = new BitmapImage();\n                using (FileStream stream = File.OpenRead(myImageFile))\n                {\n                    image.BeginInit();\n                    image.CacheOption = BitmapCacheOption.OnLoad;\n                    image.StreamSource = stream;\n                    image.EndInit();\n                }\n                myRetVal = image;\n            }\n            return myRetVal;\n        }	0
10565507	10565409	Manipulating Attributes of an XML Document	XDocument doc = XDocument.Load("test.xml");\nforeach (var id in doc.Descendants("Delta").Attributes("id"))\n{\n    id.SetValue((int) id + 1);\n}\ndoc.Save("test.xml");	0
10428476	10428425	How to access winform textbox control from another tab?	this.TheTextBoxName.Text	0
2493258	2493215	Create list of variable type	Type mytype = typeof (int);\n\n    Type listGenericType = typeof (List<>);\n\n    Type list = listGenericType.MakeGenericType(mytype);\n\n    ConstructorInfo ci = list.GetConstructor(new Type[] {});\n\n    List<int> listInt = (List<int>)ci.Invoke(new object[] {});	0
8635507	8635495	Change the variable's name only one time	Refactor -> Rename...	0
7835445	7834983	Getting the relative path from the full path	string fullPath = @"C:\User\Documents\Test\Folder2\test.pdf";\nstring partialPath = @"C:\User\Documents\";\nstring resultingPath = fullPath.Substring(partialPath.Length);	0
22754269	22753703	C#, Unable to import .p7b certificate to windows store	X509Certificate2Collection certCollection = new X509Certificate2Collection();\ncertCollection.Import(@"C:\test_public_cert.p7b");\nX509Store store = new X509Store(StoreName.AddressBook, StoreLocation.LocalMachine);\nstore.Open(OpenFlags.ReadWrite);\nstore.AddRange(certCollection);	0
8862919	8862886	How to check for a specific string in a small text file	public static bool IsStringInFile(string fileName, string searchString)\n{\n    return File.ReadAllText(fileName).Contains(searchString);\n}	0
15159464	15111708	How can i dock an asp.net: table to my web page so it (the table dock) dynamically adjusts to browser width?	.TableDock\n        {\n            overflow-x: auto;\n            overflow-y: auto;\n            //Remove the width and height completely\n            padding: 0 0 17px 0;\n        }	0
24113943	24113217	Implement pattern lock in windows phone or simple password authentication	isolated storage application settings	0
2412821	2412810	how do I retrieve an image from my resx file	rm = new ResourceManager("Images", this.GetType().Assembly); \npictureBox1.Image = (System.Drawing.Image)rm.GetObject("flag");	0
2184731	2179821	When I try to execute a stored proc ,from another stored proc, from the middle-tier -- nothing happens	INSERT INTO #AuditData (AuditDataId)\nEXEC usp_AuditSave	0
1002583	1001548	C# How to access a dropdownbox in a listview?	DropDownList ddlRole = sender as DropDownList;	0
10633179	10633119	Variable property	public int X {get; set;}	0
3694099	3694088	windows application can not write to log.txt	string path = @"c:\temp\MyTest.txt";\n    // This text is added only once to the file.\n    if (!File.Exists(path)) \n    {\n        // Create a file to write to.\n        using (StreamWriter sw = File.CreateText(path)) \n        {\n            sw.WriteLine("Hello");\n            sw.WriteLine("And");\n            sw.WriteLine("Welcome");\n        }   \n    }\n\n    // This text is always added, making the file longer over time\n    // if it is not deleted.\n    using (StreamWriter sw = File.AppendText(path)) \n    {\n        sw.WriteLine("This");\n        sw.WriteLine("is Extra");\n        sw.WriteLine("Text");\n    }	0
33026526	33024400	How to populate a docusign template using a C# dictionary?	var recipients = json["recipients"];\n       var subject = (string)json["emailSubject"];\n       var blurb = (string)json["emailBlurb"];	0
2006456	1914189	Filtering bound XML data in WPF	ICollectionView RefineList()\n    {\n        DataSourceProvider provider = (DataSourceProvider)this.FindResource("Article");\n        return CollectionViewSource.GetDefaultView(provider.Data);\n    }\n\n        private void Unread_Click(object sender, RoutedEventArgs e)\n    {\n        ICollectionView view = RefineList();\n         if (view.Filter == null)\n        {\n            view.Filter = delegate(object item)\n            {\n                return\n                int.Parse(((XmlElement)item).Attributes["read"].Value) == 0;\n            };\n        }\n        else\n        {\n            view.Filter = null;\n        }   \n    }	0
20019377	20019265	Printing a Document	private void MenuItemPrint()\n{\n   if (!FileName.Trim().Equals(""))\n   {                        \n     using(PrintDocument pd = new PrintDocument())\n     {\n        using(PrintDialog printDialog=new PrintDialog())\n        {\n          if(printDialog.ShowDialog()==DialogResult.Yes)\n          {\n          pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);                        \n          pd.Print();\n          }\n         }\n      }\n    }\n }\nprivate void pd_PrintPage(object sender, PrintPageEventArgs ev)\n{\n  ev.Graphics.DrawString(FileName, new Font("Arial", 10), Brushes.Black,\n                       ev.MarginBounds.Left, 0, new StringFormat());\n }	0
30436569	30436500	display date in its format	var formatedDate = date.getFullYear() + '/' + date.getDate() + '/' date.getDay();\n// Output is '2015/5/25'	0
19776383	19776295	How to Return Mocked Data Back With EF 6?	mockContext.Setup(m=> m.Products.First(Moq.It.IsAny<int>())).Returns(the product you want returned);	0
24619839	23524318	Require Authentication for all requests to an OWIN application	app.Use(async (context, next) =>\n        {\n            var user = context.Authentication.User;\n            if (user == null || user.Identity == null || !user.Identity.IsAuthenticated)\n            {\n                context.Authentication.Challenge();\n                return;\n            }\n            await next();\n        });	0
7942315	7942095	Google Maps v3 geocoding server-side	void GoogleGeoCode(string address)\n{\n    string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";\n\n    dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();\n    foreach (var result in googleResults.results)\n    {\n        Console.WriteLine("[" + result.geometry.location.lat + "," + result.geometry.location.lng + "] " + result.formatted_address);\n    }\n}	0
12553908	12553839	Saving a txt file to removable drive with c# wpf	string[] drives = Environment.GetLogicalDrives();\nforeach (string drive in drives)\n{\n    try\n    {\n        DriveInfo di = new DriveInfo(drive);\n        if (di.VolumeLabel == "STAR-LIGHT")\n        {\n            // code\n        }\n    }\n    catch\n    {\n        // ...\n    }\n}	0
30885106	30845461	Null reference on creating table with foreign key in Umbraco on application start	[TableName("Projects")]\n[PrimaryKey("Id", autoIncrement = true)] // This was missing\npublic class Project\n{\n    [PrimaryKeyColumn(AutoIncrement=true)]\n    public int Id { get; set; }\n\n    [Required]\n    public string Name { get; set; }\n}\n\n\n[TableName("Students")]\n[PrimaryKey("Id", autoIncrement = true)] // this was missing\n//, but only affected class with foreign key\npublic class Student\n{\n    [PrimaryKeyColumn(AutoIncrement=true)]\n    public int Id { get; set; }\n\n    [Required]\n    public string Name { get; set; }\n\n    [ForeignKey(typeof(Project))]\n    public int ProjectId { get; set; }\n}	0
6712266	6711086	Is it possible to 'relay' a socket?	while (true) {\n    acceptConnectionOnNormalPort()\n    connectToTargetPort()\n    startThreadCopyingDataFromAcceptedPortToTargetPort()\n    startThreadCopyingDataFromTargetPortToAcceptedPort()\n}	0
8299392	6962446	How to use custom type with WCF data service and EF	[WebGet(ResponseFormat = WebMessageFormat.Json)]\npublic bool ConfigurationChanged(string jsonStr)\n{\n    try\n    {\n        MyObject obj = new JavaScriptSerializer().Deserialize<MyObject>(jsonStr);\n\n        // ... do something with MyObject\n    }\n    catch (Exception)\n    {\n        throw;\n    }\n}	0
12839776	12713333	Access form values in controller, i'm trying to post whole grid back to post method ASP.net MVC	[HttpPost]\npublic ActionResult studentWeights(FormCollection formCollection)\n{\n    foreach (string _formData in formCollection)\n    {\n        var x = formCollection[_formData];\n    }\n\n}	0
21340193	21340149	Prevent my console application from closing after a .Net.Timer starts	Console.Read();	0
3554785	3554740	error in finding control in gridview	image = e.Row.FindControl("Logo") as Image;	0
10047729	10047571	Proper Approach for Temporarily Suspending a Worker Thread	class Worker\n{\n    private Thread _thread;\n\n    // Un-paused by default.\n    private ManualResetEvent _notToBePaused = new ManualResetEvent(true);\n\n    public Worker()\n    {\n        _thread = new Thread(Run)\n            {\n                IsBackground = true\n            };\n    }\n\n    /// <summary>\n    /// Thread function.\n    /// </summary>\n    private void Run()\n    {\n        while (true)\n        {\n            // Would block if paused!\n            _notToBePaused.WaitOne();\n\n            // Process some stuff here.\n        }\n    }\n\n    public void Start()\n    {\n        _thread.Start();\n    }\n\n    public void Pause()\n    {\n        _notToBePaused.Reset();\n    }\n\n    public void UnPause()\n    {\n        _notToBePaused.Set();\n    }\n}	0
5068936	5068856	Union two lists together in C#	// This will return a "union ALL" of the two select lists...\nreturn new SelectList(newSelectList.Concat(oldSelectList), "Value", "Text");\n\n//this will return a union of distinct values of the two selects,\n//PROVIDED that SelectListItem is IEquatable\nreturn new SelectList(newSelectList.Union(oldSelectList), "Value", "Text");\n\n//this will return a union of distinct values of the two selects,\n//given an implementation of an IEqualityComparer<SelectListItem> equalityComparer\n//that will semantically compare two SelectListItems\nreturn new SelectList(newSelectList.Union(oldSelectList, equalityComparer), "Value", "Text");	0
18988974	18988921	Date Format in Day, Month Day, Year	thisDate1.ToString("MMMM dd, yyyy");	0
32991187	32991058	Alias for enum value name in C#	public class B\n{\n    private const A.myEnum alias_1 = A.myEnum.value_1;\n    private const A.myEnum alias_2 = A.myEnum.value_2;\n\n    private A.myEnum[] tab = {alias_1, alias_2};\n}	0
6611446	6608368	Why doesn't reflection set a property in a Struct?	object _priceStruct = new PriceStruct(); //Box first\n    type = typeof(PriceStruct);\n    info = type.GetProperty("Value");\n    info.SetValue(_priceStruct, 32, null);\n    Console.WriteLine(((PriceStruct)_priceStruct).Value); //now unbox and get value\n\n    Debugger.Break();	0
15501497	15500205	How to export event in a DLL?	.csproject	0
7775279	7775268	How i can use a static field to keep track of how many objects have been created from a particular class	class MyClass\n{\n\n    static int instanceCount = 0;\n\n    public MyClass()\n    {\n        instanceCount++;\n    }\n\n}	0
9988494	9988395	How to map JSON to C# Objects	var yourObject =  JsonConvert.DeserializeObject<Root>(jsonstring);\n\n\npublic class Root\n{\n    public Profile[] Profile;\n}\n\npublic class Profile\n{\n    public string Name { get; set; }\n    public string Last { get; set; }\n    public Client Client { get; set; }\n    public DateTime Date { get; set; }\n}\n\npublic class Client\n{\n    public int ClientId;\n    public string Product;\n    public string Message;\n}	0
34043367	34042928	How to stream/download&play an audio from URL?	StartCoroutine(DownloadAndPlay("http://myserver.com/audio/test.ogg"));  \n\nIEnumerator DownloadAndPlay(string url)\n{\n    WWW www = new WWW(url);\n    yield return www;\n\n    AudioSource audio = GetComponent<AudioSource>();\n    audio.clip = www.GetAudioClip(false, false);\n    audio.Play();\n}	0
12487967	12487763	select only one random node from linq to xml	var qas = questions.Descendants("qa");\nint qaCount = qas.Count();\nh = qas.ElementAt(rnd.Next(0, qaCount - 1)).Element("q").Value;	0
4907556	4907540	How do I generate a URL outside of a controller in ASP.NET MVC?	public SomeReturnType MyHelper(UrlHelper url, // your other parameters)\n{\n   // Your other code\n\n   var myUrl =  url.Action("action", "controller");\n\n  // code that consumes your url\n}	0
14751296	14751105	how to set database as the source of auto-complete in C#	var autoCompleteData = new AutoCompleteStringCollection();\nautoCompleteData.add("SomeString1"); // Can be strings retrieved from database\nautoCompleteData.add("SomeString2"); // Can be strings retrieved from database\n\ntextBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend;\ntextBox.AutoCompleteSource = AutoCompleteSource.CustomSource;\ntextBox.AutoCompleteCustomSource = autoCompleteData;	0
33766334	33766276	Cannot get all the submenu items in winform in c#	static string GetText2(ToolStripMenuItem c)\n{\n    string s = c.OwnerItem.Text + @"==>" + c.Text + Environment.NewLine;\n    foreach (ToolStripMenuItem c2 in c.DropDownItems)\n    {\n        s += GetText2(c2);\n    }\n    return s;\n}	0
21503308	21503197	How to retrieve index of min value in array?	float min = float.MaxValue; //set 'min' to the maximum value of a float\nint minI, minJ;  //use if you want to track indices of the min value\n\nfor (int i = 0; i <= DistanceArray.GetUpperBound(0); i++)\n{\n    for (int j = 0; j <= DistanceArray.GetUpperBound(1); i++)\n    {\n        if (DistanceArray[i, j] <= min) //changed to '<= min' to which means if\n        {                               //there are multiple minimum values the\n            min = DistanceArray[i, j];  //one with the higher indices will be used\n            minI = i;\n            minJ = j;\n        }\n    }\n}	0
22278442	22278401	Converting Plaintext from a text box to SHA1 Then Sha1 to base 64 C#	string s = "abc";\n        byte[] data = Encoding.Unicode.GetBytes(s);\n        SHA1 algorithm = SHA1.Create();\n        byte[] hash = algorithm.ComputeHash(data);\n        string base64 = Convert.ToBase64String(hash);	0
5198878	3205053	How do I reset Visual Studio so that it once again searches for source files of DLLs while debugging?	> Common Properties\n  > Debug Source Files	0
29681514	29681416	How to access Dictionary in for loop in C#	foreach(KeyValuePair<int, string> pair in dic)\n{\n  if(pair.Key==count)\n    Console.WriteLine(pair.Value); \n}	0
2560901	2560835	How to test whether a node contains particular string or character as its text value?	var xPathDocument = new XPathDocument("myfile.xml");\nvar query = XPathExpression.Compile(@"/abc/foo[contains(text(),""testing"")]");\n\nvar navigator = xpathDocument.CreateNavigator();\nvar iterator = navigator.Select(query);\n\nwhile(iterator.MoveNext())\n{\n    Console.WriteLine(iterator.Current.Name);    \n    Console.WriteLine(iterator.Current.Value);    \n}	0
31855649	31849755	How to use ClientScript.getpostbackclienthyperlink inside INamingContainer	e.Row.Attributes["onclick"] = "__doPostBack('" + this.UniqueID + "$" + gvUserList.ID + "', 'Select$" + e.Row.RowIndex + "')";	0
3190038	3189963	How to pass a reference into and out of a class	public interface ICommented\n{\n    string Comment { get; set; }\n}\n\npublic class MyClass : ICommented\n{\n    public string Comment { get; set; }\n}\n\npublic partial class CommentEntry : Form\n{\n    public CommentEntry(Control pControl, ICommented commented)\n    {\n        InitializeComponent();\n        control = pControl;\n\n        // ***** Need a way for this to store the reference not the value. *****\n        _commented = commented;\n    }\n\n\n    private ICommented _commented;\n\n    private void CommentEntry_Closing(object sender, CancelEventArgs e)\n    {\n        _commented.Comment = tbCommentText.Text.Trim();\n    }\n}	0
1286728	1260812	ListView - Inserting Items	DirectoryInfo directoryInfo = new DirectoryInfo(@"C:\myDir");\n\nFileInfo[] files = directoryInfo.GetFiles();\n\nforeach(FileInfo fileInfo in files)\n  {\n  ListViewItem newItem = new ListViewItem();\n  newItem.Text = fileInfo.Name;\n  newItem.SubItems.Add(fileInfo.Length); //Must have a group added to the ListView (called File Size in this example)\n  listView1.Items.Add(newItem);\n  }	0
16639298	16622765	Populating 3 columns in an excel sheet from C#, without having repeated values across rows	Dictionary<String,Tuple<int,int,DateTime>> store = new Dictionary<String, Tuple<int, int, DateTime>>();\n\nfor (int i = 0; i < 500; i++)\n{\n    int n1 = rnd.Next(1,50);\n    int n2 = rnd.Next(1,50);\n    DateTime dt = RandomDay();\n\n   String key = n1.ToString() + n2.ToString() + dt.ToString();\n\n    while (store.ContainsKey(key)) {\n        n1 = rnd.Next(1,50);\n        n2 = rnd.Next(1,50);\n        dt = RandomDay();\n\n        key = n1.ToString() + n2.ToString() + dt.ToString();\n    }\n\n    store.Add(key, new Tuple(n1, n2, dt));\n}	0
14983530	14961759	Loading HTML string using HTMLAgilityPack	HtmlAgilityPack.HtmlNode.ElementsFlags.Remove("form"); \nHtmlDocument html = new HtmlDocument();\nhtml.OptionAutoCloseOnEnd = true;	0
6327311	6325759	Ensuring text wraps in a dataGridView column	private void dataGridView1_CellPainting(object sender, DataGridViewCellPaintingEventArgs e)\n{\n    if (e.Value == null)\n        return;\n    var s = e.Graphics.MeasureString(e.Value.ToString(), dataGridView1.Font);\n    if (s.Width > dataGridView1.Columns[e.ColumnIndex].Width)\n    {\n        using (\n  Brush gridBrush = new SolidBrush(this.dataGridView1.GridColor),\n  backColorBrush = new SolidBrush(e.CellStyle.BackColor))\n        {\n            e.Graphics.FillRectangle(backColorBrush, e.CellBounds);\n            e.Graphics.DrawString(e.Value.ToString(), dataGridView1.Font, Brushes.Black, e.CellBounds,StringFormat.GenericDefault);\n            dataGridView1.Rows[e.RowIndex].Height = (int)(s.Height * Math.Ceiling( s.Width / dataGridView1.Columns[e.ColumnIndex].Width)) ;\n            e.Handled = true;\n        }\n    }\n}	0
14711750	14711573	How to create a unique primary key in Entity Framework using GUID and regenerate GUID if duplicate is found?	Context.DbSet.find(MyGuid);	0
23932206	23932058	How to check if cookies are enabled or disabled in asp.net?	protected void Page_Load(object sender, EventArgs e)\n{\n    if (this.IsCookieDisabled())\n      errorMsgLabel.Text = Resources.Resource.BrowserDontSupportCookies;\n\n}\n\n\nprivate bool IsCookieDisabled()\n{\n string currentUrl = Request.RawUrl;\n\n if (Request.QueryString["cookieCheck"] == null)\n {\n     try\n     {\n            HttpCookie c = new HttpCookie("SupportCookies", "true");\n            Response.Cookies.Add(c);\n\n            if (currentUrl.IndexOf("?") > 0)\n                currentUrl = currentUrl + "&cookieCheck=true";\n            else\n                currentUrl = currentUrl + "?cookieCheck=true";\n\n            Response.Redirect(currentUrl);\n       }\n       catch(Exception ex)\n       {\n          return false;\n       }\n }\n\n if (!Request.Browser.Cookies || Request.Cookies["SupportCookies"] == null)\n      return true;\n\nreturn false;\n}	0
22075732	22075570	Pass a variable from inside an IF to the ELSE	protected void btnGuess_Click(object sender, EventArgs e)\n{\n        int randomNum = Convert.ToInt32(HttpContext.Current.Session["RANDOM"]);\n        int guessedNum = Convert.ToInt32(txtGuess.Text);\n\n        if (guessedNum < randomNum)\n        {\n            MessageBox.Show("No. Low.");\n            txtGuess.Text = "";\n        }\n        else if (guessedNum > randomNum)\n        {\n            MessageBox.Show("No. High.");\n            txtGuess.Text = "";\n        }\n        else\n        {\n            MessageBox.Show("Yes");\n            txtGuess.Text = "";\n        }\n    }\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n    if (Page.IsPostBack == false) //the code only runs once when the form is loaded.\n    {\n        Random myGenerator = new Random();\n        myGenerator = new Random();\n       int randomNum = myGenerator.Next(1, 50);\n       HttpContext.Current.Session["RANDOM"] = randomNum;\n    }\n}	0
12882617	12882589	Filling a listbox with random items from array	int limit = richcars.GetLength(0)\n for (int i = 0; i < limit ; i++)\n {\n    Random random = new Random();\n\n    int randomNumber = random.Next(0, limit);\n    if (lstBoxGarage.FindStringExact(richcars[randomNumber, 0]) == -1)\n       lstBoxGarage.Items.Add(richcars[randomNumber , 0]);\n    else\n        i--;\n }	0
20587851	20587711	want to add data into dataGridview from C# code	dataGridView1.Rows[0].Cells[0].Value = "some value";	0
29618556	29618477	How to make an error messagebox that contains a button to show error details?	try {\n    // code\n}\ncatch(Exception e) {\n    var d = new ThreadExceptionDialog(e);\n    d.ShowDialog();\n}	0
16540012	16539742	Get OperationContracts from DLL file using Assembly	var foo = from type in assembly.GetTypes()\n          where type.GetCustomAttributes(false).OfType<ServiceContractAttribute>().Any()\n          from method in type.GetMethods()\n          where method.GetCustomAttributes(false).OfType<OperationContractAttribute>().Any()\n          select method;	0
16063605	16061717	Adding a DataTable to Dynamic PDF	while (i < myDT.Rows.Count)\n{\n    while (j < myDT.Columns.Count)\n    {\n        Row newRow = table.Rows.Add(20, Font.Helvetica, 12);\n        newRow.Cells.Add(myDT.Rows[i][j].ToString());//need a default row here or way to add directly to the table\n        j++;\n    }\n    j = 0;\n    i++;\n}	0
21214570	21214492	How to add vertical scrolling to my content	ScrollBar vScrollBar1 = new VScrollBar();\nvScrollBar1.Dock = DockStyle.Right;\nvScrollBar1.Scroll += (sender, e) => { panel1.VerticalScroll.Value = vScrollBar1.Value; };\npanel1.Controls.Add(vScrollBar1);	0
28875335	28874868	How to dynamically compile source files into assembly in C#	CompilerParameters parms = new CompilerParameters\n                                           {\n                                               GenerateExecutable = false,\n                                               GenerateInMemory = true,\n                                               IncludeDebugInformation = false\n                                           };\n\n            parms.ReferencedAssemblies.Add("System.dll");\n            parms.ReferencedAssemblies.Add("System.Data.dll");\n            CodeDomProvider compiler = CSharpCodeProvider.CreateProvider("CSharp"); \n\n            return compiler.CompileAssemblyFromSource(parms, source);	0
29176159	29175800	MSIL - Can I find the Visual Studio version that was used to build/compile a .NET assembly?	.NET   Min Visual\n       Studio version\n\n1.0    2002 (7.0)\n1.1    2003 (7.1)\n2.0    2005 (8.0)\n3.0    2005 (8.0)\n3.5    2008 (9.0)\n4.0    2010 (10.0)\n4.5    2012 (11.0)\n4.5.1  2012 (11.0)\n4.5.2  2012 (11.0)\n4.6    2015 (14.0)	0
4708845	4636305	How to make a button button type (custom keyboard)	private void btnUpsidedownEx_Click(object sender, EventArgs e)\n    {\n        txtAnswer.Text = txtAnswer.Text + "??";\n        txtAnswer.Focus();\n    }	0
6017109	6017039	How to increase byte[] size at run time?	Array.Resize(ref myArray, 1024);	0
21500568	21500336	How to get file in WinRT from project path?	var folder = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFolderAsync("MyFolder");\nvar file = await folder.GetFileAsync("MyFile.txt");\n\nif (file != null)\n{\n    var content = await FileIO.ReadTextAsync(file);\n}	0
9756589	9750313	How to enable user GUI response in wcf service to trigger duplex callback to client	public class RejectService\n{\n    Dictionary<RejectInformation, Action<RejectInformation>> pendingNotifications = new Dictionary<RejectInformation, Action<RejectInformation>>();\n\n    public void SubmitNewRejectInfo(RejectInformation rejectInformation)\n    {\n       OnSubmitNewRejectInfo(new RejectInfoArgs(rejectInformation));\n       pendingNotifications.Add(rejectInformation, info => callback.RejectCallback(info));\n    }\n\n    public void SendRejectCallback(RejectInformation rejectInformation)\n    {\n       Action<RejectInformation> action;\n       if (pendingNotifications.TryGetValue(rejectInformation, out action))\n       {\n          acion(rejectInformation);\n          pendingNotifications.Remove(rejectInformation);\n       }\n    }\n}	0
16780448	16780247	How to write XPath expression to select node name from its value	//qualityNames/*[local-name()=local-name(//qualities/*[text() = '4'])]	0
30785262	30785031	Get value off querystring by it's position	string valueOfFirstQueryStringParameter = "";\nstring nameOfFirstQueryStringParameter = "";\nNameValueCollection n = Request.QueryString;\nif (n.HasKeys())\n{\n    nameOfFirstQueryStringParameter = n.GetKey(0);\n    valueOfFirstQueryStringParameter = n.Get(0);\n}	0
10924794	10924714	Separating SQL row data into multiple textboxes in C#	...\nSqlDataReader reader = command.ExecuteReader();\nif (reader.Read())\n{\n    string[] tokens = reader.GetString(0).Split(';');\n    for(int i = 0; i < tokens.Length; i++)\n    {\n        textBoxes[i].Text = tokens[i];\n    }\n}\n...	0
1296368	1296340	Nonblocking update to a DataGridView	gridView.DataSource = null;\n...stuff happens...\n\nobject[] source = dataSet; //of 2000 items\nforeach (object item in source) {  //this foreach blocks\n    dataProvider.Add(item);\n}\n\ngridView.DataSource = dataProvider;	0
32955288	32954834	Get all data from Buttons extension (Excel)	ajax.params()	0
24039947	24038599	How To Generate the same output for all clients	public static class SudokuCache\n{\n    private static Sudoku _game;\n    private static DateTime _timestamp;\n\n    public static Sudoku Game\n    {\n        get {\n            if (_timestamp.AddMinutes(20) < DateTime.Now) {\n                _game = new Sudoku();\n                _timestamp = new DateTime.Now;\n            }\n            return _game;\n        }\n}\n}\n\npublic class Sudoku { }	0
17571951	17571841	Split comma-separated values	string s = "a,b, b, c";\nstring[] values = s.Split(',');\nfor(int i = 0; i < values.Length; i++)\n{\n   values[i] = values[i].Trim();\n}	0
23375832	23368757	What benefit do I get from using ApplicationContext?	class BaseContext : ApplicationContext	0
19377896	19261150	How to resolve failed assembly verification when installing assembly into SQL Server	PERMISSION_SET = UNSAFE	0
20453688	20452511	Issue with transparent images with a transparent background	// mStaff: the MusicStaff object\n// mNote: the MusicNote object\nmStaff.Children.Add(mNote);	0
3399971	3091511	How to send a Font File to a Zebra Printer (MZ 220) via .Net SDK?	! CISDFCRC16\n<crc>          // 4 digit hex CRC.  Enter 0000 to turn off CRC check.\n<filename>     // file name with extension.  8.3 filenames only.\n<size>         // eight digit hex file size in bytes.\n<checksum>     // four digit hex checksum.  Enter 0000 to turn off checksum validation.\n<data>         // Binary data to store	0
5820598	5820577	How do i accept and process an incoming parameter via URL	Request.QueryString["parametername"]	0
18621784	18600060	Windows Store Application Metronome Stop Button Not Working	public void Start(int bbm)\n{\n    _timer.Interval = new TimeSpan(0, 0, 0, 0, 500);\n    _timer.Start();\n}\npublic void Stop()\n{\n    _timer.Stop();\n}	0
9320338	9319675	Order/Sort a nested generic list	var orderedMovies =\n    movies.OrderBy(movie => \n                    String.Join(",", movie.Directors\n                                             .OrderBy(dir => dir.Name)\n                                             .Select(dir => dir.Name)\n                    )\n    );	0
688347	688336	Show line number in exception handling	ex.ToString()	0
6572289	6572073	HtmlGenericControl Without Tag	myUserControl.Controls.Add(new LiteralControl(myHTMLstring));	0
12026778	12026766	How can I do a Navigate from another thread?	Dispatcher.BeginInvoke	0
9217815	9217640	How to add new child node to existing child node	protected override void SaveApsXml(System.Xml.XmlNode node)\n{\n    base.SaveApsXml(node);            \n    node.AppendNewChild("EventTime").SetElementText(this.EventTime.ToString(ApsMessage.DateTimeFormat));\n    var track = node.AppendNewChild("Track");\n    track.SetAttribute("name", this.Track);\n    this.SequenceCar.SaveApsXml(track.AppendNewChild("Car"));\n}	0
25333753	25333664	MVVM Update Property A when Property B changes	NotifyPropertyChanged(m => m.RateTableDataView);	0
4440388	4440378	Put the Query result of MySql in to a C# list or array?	public void CreateMySqlDataReader(string mySelectQuery, MySqlConnection myConnection) \n {\n    MySqlCommand myCommand = new MySqlCommand(mySelectQuery, myConnection);\n    myConnection.Open();\n    MySqlDataReader myReader;\n    myReader = myCommand.ExecuteReader();\n    try\n    {\n      while(myReader.Read()) \n      {\n        Console.WriteLine(myReader.GetString(0));\n      }\n    }\n    finally\n    {\n      myReader.Close();\n      myConnection.Close();\n    }\n }	0
22004644	22004488	Conversion failed when converting date and/or time from character string. Inserting value from datetimepicker	dateTimePicker1.Value.Date	0
1598080	1598070	C# equivalent of C++ map<string,double>	var accounts = new Dictionary<string, double>();\n\n// Initialise to zero...\n\naccounts["Fred"] = 0;\naccounts["George"] = 0;\naccounts["Fred"] = 0;\n\n// Add cash.\naccounts["Fred"] += 4.56;\naccounts["George"] += 1.00;\naccounts["Fred"] += 1.00;\n\nConsole.WriteLine("Fred owes me ${0}", accounts["Fred"]);	0
25868458	25858929	How to copy a column of DataGrid to an array C# WPF	// You have a list of Data elements List<Data> gridData that is the data \n// source of your DataGrid\ndouble[] periods = gridData.Select(x => x.Period).ToArray();	0
10830497	10823680	C# Reflection: Emit DateTime Property Value	ctorDefaultIL.Emit(OpCodes.Ldc_I8, dateVal.Ticks);\nctorDefaultIL.Emit(OpCodes.Newobj, \n  typeof(DateTime).GetConstructor(new[] { typeof(long) }));	0
7333825	7333505	TFS2010: How to link a WorkItem to a ChangeSet	WorkItemStore store = new WorkItemStore(collection);\nChangeset changeset = service.GetChangeset(123, true, true);\n\nWorkItem item = new WorkItem(project.WorkItemTypes["CustomItem"]);     \nitem.Links.Add(new ExternalLink(store.RegisteredLinkTypes[ArtifactLinkIds.Changeset], changeset.ArtifactUri.AbsoluteUri));       \nitem.Fields["CustomField1"].Value = someValue;\nitem.Fields["CustomField2"].Value = someValue;\nitem.Fields["CustomField3"].Value = someValue;\nitem.Validate();\nitem.Save();	0
5330903	5330580	How to partition a LINQ to Objects query?	var topShifts = from s in shifts.GroupBy(s => s.CompanyId)\n                        from a in s.GroupBy(b => b.TimeSlot)\n                        select a.OrderBy(p => p.Priority).First();	0
22718537	22718043	How to pull all staffNames from Department in AD and place in a dropdown?	string connection = ConfigurationManager.ConnectionStrings["ADConnection"].ToString();\n\nDirectorySearcher dssearch = new DirectorySearcher(connection);\ndssearch.Filter = "(&(objectCategory=Person))";\ndssearch.Filter = "(sAMAccountName=" + current_User + ")";\n\nSearchResultCollection searchResult = dssearch.FindAll();\n\nforeach (SearchResult srUSers in searchResult)\n{\n    DirectoryEntry de = srUsers.GetDirectoryEntry();\n    dropDownList1.Items.Add(de.Name.ToString());\n}	0
33647580	33647352	MethodInvoker for a button	private void UpdateStatus(String message)\n{\n    if (this.InvokeRequired)\n        this.Invoke((MethodInvoker)delegate\n        {\n            UpdateStatus(message);\n        });\n    else\n        label1.Text = message;\n}	0
1651005	1569032	How can I reorder columns in a listview with the same result as drag and drop	for (int ix = 0; ix < listView.Columns.Count; ix++)\n{\n  ColumnHeader columnHeader = listView.Columns[ix];\n  int displayIndex = Settings.GetSettingInt("List", columnHeader.Text + "Index");\n  columnHeader.DisplayIndex = displayIndex;\n}	0
9366414	9365658	How to fetch only all webmethod in class at runtime using reflaction class?	var methods = typeof(Service1).GetMethods()\n                              .Where(meth => meth.GetCustomAttributes(true)\n                                                 .Where(attr => attr is OperationContractAttribute)\n                                                 .Count() > 0);	0
22253012	22252814	Automatically set the scroll to end of file?	void ScrollToBottom()\n{\n   txtLogEntries.SelectionStart = txtLogEntries.Text.Length;\n   txtLogEntries.ScrollToCaret();\n}	0
29832649	29375254	WPF RichTextBox get selected element	Hyperlink GetHyperlinkAtSelection()\n{\n  var selectedPointer = rtb.Selection.GetNextInsertionPosition(forward)\n\n  if(sp == null)\n    return;\n\n  var para = sp.Paragraph;\n\n  var hyperlink = para.Inlines.FirstOrDefault(x => \n    x.ContentStart.CompareTo(sp) == -1 && x.ContentEnd.CompareTo(sp) == 1);\n\n  return hyperlink as Hyperlink;\n}	0
23729804	23728074	How do I get Geolocation of a street address in Windows Phone 8.1 Universal App?	// Nearby location to use as a query hint.\nBasicGeoposition queryHint = new BasicGeoposition();\n    // DALLAS\nqueryHint.Latitude = 32.7758;\nqueryHint.Longitude = -96.7967;\n\nGeopoint hintPoint = new Geopoint(queryHint);\n\nMapLocationFinderResult result = await MapLocationFinder.FindLocationsAsync(\n                        "street, city, state zip",\n                        hintPoint,\n                        3);\n\nif (result.Status == MapLocationFinderStatus.Success)\n{\n    if (result.Locations != null && result.Locations.Count > 0)\n    {\n        Uri uri = new Uri("ms-drive-to:?destination.latitude=" + result.Locations[0].Point.Position.Latitude.ToString() +\n            "&destination.longitude=" + result.Locations[0].Point.Position.Longitude.ToString() + "&destination.name=" + "myhome");\n\n        var success = await Windows.System.Launcher.LaunchUriAsync(uri);\n    }\n}	0
1009982	1009913	Close modal dialog from external thread - C#	partial class TimedModalForm : Form\n{\n    private Timer timer;\n\n    public TimedModalForm()\n    {\n        InitializeComponent();\n\n        timer = new Timer();\n        timer.Interval = 3000;\n        timer.Tick += CloseForm;\n        timer.Start();\n    }\n\n    private void CloseForm(object sender, EventArgs e)\n    {\n        timer.Stop();\n        timer.Dispose();\n        this.DialogResult = DialogResult.OK;\n    }\n}	0
9743945	9734615	Having trouble in Datasource for Telerik RadGrid	protected void RadGrid1_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)\n        {\n            string PhoneID = RadComboBox1.SelectedItem.Value;\n            RadGrid1.DataSource = GetDataTable(string.Format("SELECT * FROM [Products] WHERE ([ProductID] = {0})", PhoneID));\n        }	0
22938626	22938567	Invalid cell value - Server Error in '/' Application	ExcelLibrary.DataSetHelper.CreateWorkbook(String filePath, DataSet dataset) +644	0
4620486	4620437	evaluate an arithmetic expression stored in a string (C#)	var engine = VsaEngine.CreateEngine();\nEval.JScriptEvaluate(mySum, engine);	0
15257363	15257132	Entity Framework Datagridview filter	var myQuery = from movie in myContext.Movies\n          where movie.genre.Any(g=>g.Id == ((Genre)listBox.SelectedItem).Id)\n          select movie;	0
15875027	15874932	Calendar date reverting to initialised date C#	protected void Page_Load(object sender, EventArgs e)\n{\n    if(!Page.IsPostBack)\n    {\n        visitDateCal.SelectedDate = DateTime.Today; //defaults to today's date\n    }\n}	0
7348945	7348669	Entity Framework Multiple Stored Procedures	right click --> Update Model from Database	0
13393839	13390313	POS Application Development - Receipt Printing	OPOSPOSPrinter.Open "MyPrinter"    ' LDN of your printer   \nOPOSPOSPrinter.Claim 500           ' Timeout   \nOPOSPOSPrinter.DeviceEnabled = True  \n\n'- Print   \nOPOSPOSPrinter.PrintNormal 2, "Hello world"  \n\n'- Close the printer   \nIf OPOSPOSPrinter.Claimed then   \n   OPOSPOSPrinter.Release   \nEnd If  \nOPOSPOSPrinter.Close	0
29542504	29526019	Building a dynamic javascript function with c#	Html.renderpartial("othercase")	0
14960149	14959969	How to load parsed aspx into string variable	System.IO.StringWriter htmlStringWriter = new System.IO.StringWriter();\nServer.Execute("Page.aspx", htmlStringWriter);\nstring htmlOutput = htmlStringWriter.GetStringBuilder().ToString();	0
22246000	22245590	Best Linq Syntax for To Create List for JQuery Autocomplete	IEnumerable<MyMeasure> interList = \n    MyMeasure.Distinct(new MyMeasure.NameComparer())\n             .Where(cmo => cmo.CompanyMeasureName\n                              .ToLower()\n                              .Contains(term.ToLower())).Select(m => m.CompanyMeasure);	0
13675795	13675775	Equivalent of Substring as a RegularExpression	.{y}(.{x}).*	0
21457431	21456004	'/' character in routing parameter	routes.MapRoute(\n                    name: "haber2",\n                    url: "{noFollow*}-{id}.html",\n                    defaults: new { controller = "Anasayfa", action = "HaberID" },\n                    constraints: new {id = "\\d+"}\n                );	0
23993968	23962080	In Unity and NGUI, a prefab, onClick notify works on public function but the boolean loses it's value in update	static bool rotate;	0
25358930	25245679	Round off kendo ui grid aggregate to the nearest whole number	column.Bound(c => c.AchievedPercentage).Format("{0} %").HtmlAttributes(new { style = "text-align: center;" }).HeaderHtmlAttributes(new { style = "text-align: center;", title = "Assessment Progress" }).ClientFooterTemplate("Overall: #= kendo.toString(average, '0') #%");	0
3149283	3149275	How do you access the children of a WPF Canvas class?	foreach (UIElement child in canvas.Children)\n{\n    // ...\n}\n// Or: \nint index = 0;\nvar childByIndex = canvas.Children[index];	0
24697384	24125177	Make form stay in front of other windows without resizing or moving it	.TopMost = true	0
19742682	19738383	How to deploy IHttpHandler code to IIS	"%windir%\Microsoft.NET\Framework\"YOUR .NET VERSION"\aspnet_regiis.exe" -i	0
25924314	25924107	How NOT to block control of a button?	delegate void Work();\n\nprivate void Button_Click(object sender, RoutedEventArgs e)\n{\n    new Work(WorkOne).BeginInvoke(null, null);\n}\n\nprivate void WorkOne()\n{\n    int x = 0;\n    while (r == false)\n    {\n        listBox.Dispatcher.Invoke(new Action(() =>{ listBox.Items.Add(x++); }));\n        System.Threading.Thread.Sleep(x);\n    }\n}\n\nprivate void btnStop_Click(object sender, RoutedEventArgs e)\n{\n        r = true;\n}	0
4360755	4360721	Is it possible to assign the result of an SQL to a variable?	var command = new SqlCommand("SELECT TOP 1 age FROM example_table");\nvar ageValue = command.ExecuteScalar() as int?;	0
12853147	12853034	Write file to windows share using Streamreader	web.config	0
9991802	9991352	How do I export data to a CSV file in C# making sure that Excel can work with it?	var lines = new string[10][];\n\nvar csv = string.Join("\r\n", lines.Select(words =>\n              string.Join(",", words.Select(word =>\n                  "\"" + word.Replace("\"", "\"\"") + "\"")))));\n\nFile.WriteAllText("file.csv", csv);	0
24056685	23994780	How to change SecureConversationVersion property in SessionSecurityToken class	public class MyTokenHandler : SessionSecurityTokenHandler\n{\n    public override void WriteToken(XmlWriter writer, SecurityToken token)\n    {\n        SessionSecurityToken sessionSecurityToken = token as SessionSecurityToken;\n        sessionSecurityToken.IsReferenceMode = true;\n        string ns = "http://schemas.xmlsoap.org/ws/2005/02/sc";\n        string localName = "SecurityContextToken";\n        string localName2 = "Identifier";\n\n        XmlDictionaryWriter xmlDictionaryWriter;\n\n        if (writer is XmlDictionaryWriter)\n        {\n            xmlDictionaryWriter = (XmlDictionaryWriter)writer;\n        }\n        else\n        {\n            xmlDictionaryWriter = XmlDictionaryWriter.CreateDictionaryWriter(writer);\n        }\n\n        xmlDictionaryWriter.WriteStartElement(localName, ns);\n        xmlDictionaryWriter.WriteElementString(localName2, ns, sessionSecurityToken.ContextId.ToString());\n        xmlDictionaryWriter.WriteEndElement();\n        xmlDictionaryWriter.Flush();\n    }\n}	0
12161889	12130605	Disable editing child controls of custom DevComponents.DotNetBar control	[Designer("System.Windows.Forms.Design.ParentControlDesigner, System.Design", typeof(IDesigner))]\npublic partial class barFloorsGrouping : Bar\n{\n...\n}	0
27781250	27781132	How to set Crystal reports Connection info	Integrated Security=true	0
886467	846927	is it possible to insert microsoft word document editor to own application using PIA	framerControl.Open(@"C:\SomeDocument.doc");	0
6813817	6812492	How to transform XMLDocument using XSLT in C# 2.0	XslCompiledTransform xslTransform = new XslCompiledTransform();\n        StringWriter writer = new StringWriter();          \n        xslTransform.Load("xslt/RenderDestinationTabXML.xslt");\n        xslTransform.Transform(doc.CreateNavigator(),null, writer);\n        return writer.ToString();	0
31513369	31470230	Change Visio default drawing units	Page.DrawRectangle	0
23360454	23360313	C# How to run delayed method in between timer ticks	private int Counter;\n\nprivate void cmdGo_Click(object sender, EventArgs e)\n{\n    System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();\n    t.Interval = 60000; // specify interval time - 1 minute\n    t.Tick += new EventHandler(timer_Tick);\n    t.Start();\n}\n\n// Every 1 min this timer fires...\nvoid timer_Tick(object sender, EventArgs e)\n{\n    // If it has been 16 minutes then run RunMethod1\n    if (++Counter >= 16)\n    {\n        Counter = 0;\n        RunMethod1();         \n        return;\n    }\n\n    // Not yet been 16 minutes so just run RunMethod2\n    RunMethod2();\n}	0
3873403	3873356	Where is a .net Application Icon Stored?	var icon = Icon.ExtractAssociatedIcon(Application.ExecutablePath);	0
34287738	34287481	DateTime property stays at 01/01/0001	var entity = new UDetails()\n{\n    // ...\n\n    Email = User.Identity.Name,\n    RegesterDate = DateTime.Now,\n    UDetailsId = User.Identity.GetUserId()      \n\n    // ...\n};	0
17068540	17067301	transfer DTO to ViewModel	LoadSourceDetail obj = FillLoadSourceDetail ();// fill from source or somewhere\n\n     // check for null before\n    ReportingEntity = obj.ReportingEntity\n                     .Select(x => new ReportingEntityViewModel() \n                        { \n                           ReportingEntityCode  = x.ReportingEntityCode,\n                           ReportingEntityDesc  x.ReportingEntityDesc\n                         })\n                     .ToList(); // here is  'x' is of type ReportingEntityDetail	0
3417318	3416050	I want to kill a few ClickOnce applications - can I access a ClickOnce "installation folder URL" from code?	try\n            {\n                // The next four lines probe for the update server.\n                // If the update server cannot be reached, an exception will be thrown by the GetResponse method.\n                string testURL = ApplicationDeployment.CurrentDeployment.UpdateLocation.ToString();\n                HttpWebRequest webRequest = WebRequest.Create(testURL) as HttpWebRequest;\n                webRequest.Proxy.Credentials = CredentialCache.DefaultCredentials;\n                HttpWebResponse webResponse = webRequest.GetResponse() as HttpWebResponse;\n\n                // I discard the webResponse and go on to do a programmatic update here - YMMV\n            }\n            catch (WebException ex)\n            {\n                // handle the exception\n            }	0
6259218	6259209	C# remove elements in list starting with #	myList.RemoveAll(x => x.BeginsWith("#"));	0
32910105	32910034	Password value missing after POST	if (result)\n{\n    return RedirectToAction("GetSettings");\n}	0
12538104	12525322	How to use wkHtmltoPdf to generate PDf files from statcic html files in C#	var pi = new ProcessStartInfo(@"c:\wkhtmltopdf\wkhtmltopdf.exe");\npi.CreateNoWindow = true;\npi.UseShellExecute = false;\npi.WorkingDirectory = @"c:\wkhtmltopdf\";\npi.Arguments = "http://www.google.com gogl.pdf";\n\nusing (var process = Process.Start(pi))\n{\n    process.WaitForExit(99999);\n    Debug.WriteLine(process.ExitCode);\n}	0
21158279	21158223	Proper way to Categorize by a Property	var result = g.GroupBy(x => x.City, (key, group) => new {\n                           city = key,\n                           employees = group.Select(emp => new {\n                               fullname = emp.FirstName + " " + emp.LastName,\n                               title = emp.Title\n                           })\n                       });	0
1498626	1498500	event handlers for items of contextmenustrip	using System;\n            using System.Windows.Forms;\n            namespace WindowsFormsApplication6\n            {\nstatic class Program\n{\n    /// <summary>\n    /// The main entry point for the application.\n    /// </summary>\n    [STAThread]\n    static void Main()\n    {\n        using (Form form = new Form())\n        {\n            form.ContextMenuStrip = new ContextMenuStrip();\n            ToolStripItem addMenuItem = form.ContextMenuStrip.Items.Add("Add");\n            ToolStripItem deleteMenuItem = form.ContextMenuStrip.Items.Add("Delete");\n\n            form.ContextMenuStrip.ItemClicked += (sender, e) =>\n          {\n              if (e.ClickedItem == addMenuItem)\n              {\n                  MessageBox.Show("Add Menu Item Clicked.");\n              }\n              if (e.ClickedItem == deleteMenuItem)\n              {\n                  MessageBox.Show("Delete Menu Item Clicked.");\n              }\n          };\n            Application.Run(form);\n        }\n    }\n}	0
25755801	25755800	Draw a colour bitmap as greyscale in WPF	using System;\nusing System.Windows;\nusing System.Windows.Media;\nusing System.Windows.Media.Imaging;\n\nvoid DrawBitmapGreyscale(DrawingContext dc, string filename, int x, int y, int width, int height)\n{\n    // Load the bitmap into a bitmap image object\n    BitmapImage bitmap = new BitmapImage();\n    bitmap.BeginInit();\n    bitmap.CacheOption = BitmapCacheOption.OnLoad;\n    bitmap.UriSource = new Uri(filename);\n    bitmap.EndInit();\n\n    // Convert the bitmap to greyscale, and draw it.\n    FormatConvertedBitmap bitmapGreyscale = new FormatConvertedBitmap(bitmap, PixelFormats.Gray8, BitmapPalettes.Gray256, 0.0);\n    dc.DrawImage(bitmapGreyscale, new Rect(x, y, width, height));\n}	0
5379327	5379301	C# Parent Class with interface based properties that can change per subclassed declaration	public class OtherClass<T> where T : IBaseline\n{\n    public T GenericInstance { get; private set;}\n\n    public OtherClass(T genericInstance)\n    {\n        this.GenericInstance = genericInstance;\n    }\n}	0
1436097	1436059	Windows form with a transparent background that cannot be clicked through	protected override void WndProc(ref Message m) {\n    switch (m.Msg) {\n    case 0x84: // this is WM_NCHITTEST\n        base.WndProc(ref m);\n        if ((/*m.LParam.ToInt32() >> 16 and m.LParam.ToInt32() & 0xffff fit in your transparen region*/) \n          && m.Result.ToInt32() == 1) {\n            m.Result = new IntPtr(2);   // HTCAPTION\n        }\n        break;\n    default:\n        base.WndProc(ref m);\n        break;\n    }\n}	0
3178560	3178403	Help with LINQ statement	events.OrderBy(ev => ev.Appointments.Min(app => app.StartTime)).First().StartTime;	0
901679	901670	IEnumerable and string array - find matching values	var selected = MultiSelectList.Items\n  .Cast<IDName>()\n  .Where(x => MultiSelectList.SelectedItems.Contains(x.Name));	0
5075218	5075104	Read specific div from HttpResponse	HtmlWeb web = new HtmlWeb();\nHtmlDocument doc = web.Load("http://jsbin.com/owobe3");\nHtmlNode rateNode = doc.DocumentNode.SelectSingleNode("//div[@id='rate']");\nstring rate = rateNode.InnerText;	0
5483094	5229159	How to find the all LAN systems mode using c# whether the system is in log off or hibernate	using System.Net.NetworkInformation;\n  public bool IsNetworkLikelyAvailable() \n  {\n  return NetworkInterface\n  .GetAllNetworkInterfaces()\n  .Any(x => x.OperationalStatus == OperationalStatus.Up);\n    }	0
13992789	13974558	POST/PUT request with Portable Library	using (var stream = await request.GetRequestStreamAsync())\n{\n    stream.Write(dataBytes, 0, dataBytes.Length);\n}	0
33011810	33010783	C# - webdriver: How to refer to the object	var alerts = driver.FindElements(By.CssSelector("div.alert.alert-dismissable.alert-info"));\nAssert.IsTrue(alerts.Any(element => element.Text.Contains("Good morning")));	0
4980347	4980005	.NET - copy data from specific segment:offset	int bufSize = 12;\n\n        IntPtr ptr = (IntPtr) (0xffff *16U + 5);                  \n\n        byte[] data = new byte[bufSize];\n        Marshal.Copy(ptr, data, 0, bufSize);	0
6202260	6202190	Auto save - WPF C#	DispatcherTimer autosaveTimer = new DispatcherTimer(TimeSpan.FromSeconds(autosaveInterval), DispatcherPriority.Background, new EventHandler(DoAutoSave), Application.Current.Dispatcher);\n\n    private void DoAutoSave(object sender, EventArgs e)\n    {\n        // Enter save logic here...\n    }	0
7983077	7980589	Usage of AspectPriority	[Trace(AttributePriority = 2)]\n[HandleError(AttributePriority = 1)]\npublic void MyMethod()\n{\n\n}	0
29900486	29899883	How to loop value in C# using SQL Server	con.Open();\ncmd = new SqlCommand("SELECT Emp_FName,Emp_LName,T_Subject from Employee where Emp_Position = 'Teacher'", con);\nrdr = cmd.ExecuteReader();\n\ntxtTeacher.Items.Clear;\n    while (rdr.Read())\n    {\n        string sub = rdr["T_Subject"].ToString();\n        string fname = rdr["Emp_FName"].ToString();\n        string lname = rdr["Emp_LName"].ToString();\n        string fulname = fname + ' ' + lname;\n\n    if (ComboSubDep.Text == sub)\n    {\n        txtTeacher.Items.Add(fulname);\n    }\n}	0
414314	414283	How can I handle a NULLable Int column returned from a stored procedure in LINQ to SQL	Nullable<int> or int?	0
34192589	34192513	Read the byte format of txt file in c#	var bytesFromFile = System.IO.File.ReadAllBytes(@"My file here");\nConsole.WriteLine(Encoding.UTF8.GetString(bytesFromFile));\nConsole.ReadKey();	0
26717192	26716715	c# winforms: searching for datagridview event that will fire after changing cell value AND cell focus	datagridview_CellValidating(object sender, DataGridViewCellValidatingEventArgs e)\n{\n  if(e.FormattedValue == (theOldValue))\n  {\n      changed = false; \n      currentIndexRow= e.RowIndex; \n      currentIndexColumn= e.ColumnIndex; \n      e.cancel = true; \n\n  }\n}\ndatagridview_SelectionChanged(object sender, EventArgs e)\n{\n   if(!changed)\n    datagridview.CurrentCell = datagridview.Rows[currentIndexRow].Cells[currentIndexColumn];\n}	0
26976870	26976252	WP Parse Enclosure url	XElement element = item.Element("enclosure"); //new element\n\n        int length = (int)element.Attribute("length"); //seprate attributes\n        string type = (string)element.Attribute("type");\n        string url = (string)element.Attribute("url");\n\n        rssItem.FeedUrl = url; // use the result	0
1428429	1428376	Aggregate a List<int> to a string using (i, j) => i + "delimiter" + j	string s = list.Aggregate<int, string>(String.Empty, (x, y) => (x.Length > 0 ? x + "^" : x) + y.ToString());	0
6297649	6186109	Passing values from 2 dropdown boxes	string caseType = null;\n        if (!String.IsNullOrEmpty(viewModel.CaseTypeValue))\n        {\n            caseType = HttpUtility.UrlEncode(viewModel.CaseTypeValue, System.Text.Encoding.Default);\n        }	0
9939366	9939267	Regular expression replace $(Key) in text file with value from dictionary	var replacements = new Dictionary<string,string>();\n//populate the dictionary\nstring file = System.IO.File.ReadAllText("filepath");\nfile = Regex.Replace(file, @"\$\((?<key>[^)]+)\)", new MatchEvaluator(m => replacements.ContainsKey(m.Groups["key"].Value) ? replacements[m.Groups["key"].Value] : m.Value));	0
16461596	14573757	DisplayAttribute doesn't localize its properties in model	public object Convert(object value, Type targetType, object parameter, CultureInfo culture)\n{\n  var mp = parameter as MetadataParameters;\n  var modelPropertyInfo = mp.ModelType.GetProperty(mp.ModelProperty);\n  var attribute = modelPropertyInfo\n      .GetCustomAttributes(true)\n      .Cast<Attribute>()\n      .FirstOrDefault(memberInfo => memberInfo.GetType() == mp.AttributeType);\n\n  // We have to call the GetXXX methods on the attribute to get a localised result.\n  //return ((DisplayAttribute)attribute).GetName();\n  var result = attribute\n    .GetType()\n    .InvokeMember(\n      "Get" + mp.AttributeProperty,\n      BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public,\n      null,\n      attribute,\n      new object[0]); \n  return result;\n}	0
21325264	21288965	find dynamically added controls	foreach (TabelRow row in Table1.Rows)\n{\n    if(row.Cells.Count > 0)\n    {\n        if (row.Cells[1].Controls.Count > 0 && row.Cells[1].Controls[0].GetType() ==  typeof(DropDownList))\n        {\n            Response.Write(a.SelectedValue); \n        }\n    }\n}	0
2730314	2730299	Search string to find Filename	System.IO.Path.GetFileName("//houtestserver/common/file1.pdf");	0
14096127	14096050	Mocking out a local variable in C#	public interface IDependency\n{\n    void DoSomeStuff();\n}\n\npublic class ClassUnderTest\n{\n    private IDependency _dependency;\n\n    public ClassUnderTest(IDependency dependency)\n    {\n        _dependency = dependency;\n    }\n\n    public ClassUnderTest() : this(new Dependency())\n    {}\n\n    public void ImportantStuff()\n    {\n        _dependency.DoSomeStuff();\n    }\n}	0
23933165	23932591	WPF ComboBox - is it possible to insert your own text?	public void AddValue(string newGuid)\n        {\n            Guid g  =  new Guid(newGuid);\n            m_TheValues.Add(g); \n        }	0
5306442	5306311	errors trying to insert into mysql database?	OdbcCommand cmd = new OdbcCommand("INSERT INTO User (Email, FirstName, SecondName, DOB, Location, Aboutme) VALUES ("+ email +","+ firstname+","+SecondName+","+DOB+","+Location+","+Aboutme+")",cn);	0
8146266	8145853	How can I use Entity Framework to search only the Store not the local data?	Child child = GetChildFromSomewhere();\nParent parent = GetParentFromSomewhere();\n\n// Don't do this\nchild.ParentId = parent.ParentId;\n\n// Use this instead\nchild.Parent = parent;	0
19711493	19711219	Count parent nodes in XML Document	XDocument.Parse(@"...").Descendants().Where(n => n.Elements().Any()).Select(n => n.Name).Distinct().Count();	0
2842903	2842822	How to remove a certain row from DataTable?	DataRow[] rows;\nrows=dataTable.Select("userCity = 'Munich'");\nforeach(DataRow r in rows)\nr.Delete();	0
16363203	16354712	How to programmatically create firebird database?	...\nusing FirebirdSql.Data.Firebird;\n...\n\nFbConnectionStringBuilder builder = new FbConnectionStringBuilder();\nbuilder.DataSource = "COMPUTER_WITH_DATABASE";\nbuilder.UserID = "SYSDBA";\nbuilder.Password = "m*******y";\nbuilder.Database = @"c:\database.fdb";\nbuilder.ServerType = FbServerType.Default;\n\nFbConnection.CreateDatabase(builder.ConnectionString);	0
4736839	4736831	Open webpage programmatically and retrieve its html contain as a string	var html = new WebClient()\n               .DownloadString("the facebook account url goes here");	0
32879694	32877770	Set Ajax Tab Container Width to 100%	container.Width = Unit.Percentage(100);	0
6612376	6602315	MSChart X axis with fixed length	chart1.ChartAreas[0].AxisX.Minimum = 7;\nchart1.ChartAreas[0].AxisX.Maximum = 12;	0
14877775	14877524	Content of HttpResponseMessage as JSON	Request.CreateResponse<Response>(HttpStatusCode.OK, new Response() { responseCode = Response.ResponseCodes.ItemNotFound })	0
17198270	17197862	Getting and setting the value of a specific part of a large multi-dimensional array	int[, ,] a = new int[2, 2, 3]{\n        { {1,2,3}, {4,5,6} },\n        { {7,8,9}, {10,11,12}  }\n};\nint x = (int)a.GetValue(0,1,2); // this returns 6\n\nint[] nArray = new int[] { 1, 1, 0 };\nx = (int)a.GetValue(nArray); // this returns 10	0
19317844	19317517	Ways to prevent a class file from looking verbose when using multiple properties	{ get; set; }	0
19513162	19492539	Viewstate history gets affected by activity on a different page	protected override PageStatePersister PageStatePersister\n{\n    get\n    {\n        return new HiddenFieldPageStatePersister(this);\n    }\n}	0
32136543	32135407	Formatting a spreadsheet using c# oledbc	public List<Checklist> Provide()\n{\n  List<Checklist> checklists = new List<Checklist>();\n  using (var reader = ExcelReaderFactory.CreateOpenXmlReader(m_Stream))\n   {\n                while (reader.Read())\n                {\n                    Checklist checklist = new Checklist();\n\n                     checklist.Description = reader.GetString(1);\n                     checklist.View = reader.GetString(2);\n                     checklist.Organ = reader.GetString(3);\n                     checklists.Add(checklist);\n                 }\n                return checklists; \n    }\n}	0
10158200	10158162	Compare system date with a date field in SQL	object dobVal = null;\nwhile ((dobVal= reader.Read()) != null)\n{\n  var storedDob = Convert.ToDateTime(dobVal.ToString());\n\n  if(storedDob.Month == DateTime.Now.Month && \n     storedDob.Day == DateTime.Now.Day)\n  {\n    Session["Birthday"] = "Happy Birthday";\n  }\n}	0
13794255	13793788	How do I get the grid parent of my control?	private void button1_Click(object sender, RoutedEventArgs e)\n{\n    Grid x = (sender as Button).Parent as Grid;\n}	0
14150671	14150619	How to kill my process? Without killing process which belong another users	Marshal.FinalReleaseComObject(xlWorkSheet);\nxlWorkBook.Close(false);\nMarshal.FinalReleaseComObject(xlWorkBook);\nxlApp.Quit();\nMarshal.FinalReleaseComObject(xlApp)	0
10010675	10010541	Linq to SQL translation to SQL syntax	var results = from t1 in Table1\n   from t2 in Table2\n   where t1.ID = t2.AnotherID\n   join t3 in Table3 on t1.ID equals t3.AnotherID into joined\n   from j in joined.DefaultIfEmpty()\n   select new {t1, t2, t3 = j}	0
16315949	16315820	How to attach event to this hyperlink button	protected void OnRowDataBound(object sender, GridViewRowEventArgs e)\n    {\n        // this will apply the action in the lambda expression to all controls or sub-controls of the row matching type LinkButton  \n        // (you may have a different control type and you may want to alter your lambda expression to check that the control matched is really the control you want to manipulate)\n        SearchControls<LinkButton>(e.Row, button => button.OnClientClick = "alert('here');");\n    }\n\n    // recursive Control search function\n    private void SearchControls<T>(Control start, Action<T> itemMatch)\n    {\n        foreach (var c in start.Controls.OfType<T>())\n            itemMatch(c);\n\n        foreach (var c in start.Controls.OfType<Control>())\n            SearchControls<T>(c, itemMatch);\n    }	0
23280109	23279409	Populating a DataTable with reflection	foreach (var dataItem in listOfData)\n{\n    DataRow row = dataTable.NewRow();\n\n    for (int i = 0; i < props.Length; i++)\n    {\n       row[i] = props[i].GetValue(dataItem);\n    }\n\n    dataTable.Rows.Add(row);\n}	0
23501848	23458997	Get dynamic hubtile name to create secondary tiles	string clickedElement = ((System.Windows.FrameworkElement)(sender)).Tag;	0
22141550	22138546	Call method from managed dll c#	bvlsFortran.BV	0
5208110	5198315	What workflow framework to use in C#	.Yield()	0
17563697	17561185	How to center the images with the page tab?	public class BrunoTabControl : TabControl\n{\n    protected override void OnDrawItem(System.Windows.Forms.DrawItemEventArgs e)\n    {\n        if (ImageList == null) return;\n        int imageIndex = TabPages[e.Index].ImageIndex;\n        if (imageIndex >= 0) ImageList.Draw(e.Graphics, 0, 0, imageIndex);\n    }\n}	0
6407499	6407487	How to execute next loop after specific time?	using System.Threading;\n\nforeach(..) { } // your for or foreach or any code you want\n\nThread.Sleep(5000); // pause the current thread on x milliseconds\n\nforeach(..) { }\n\nThread.Sleep(3000);\n\nforeach(..) { }	0
12538347	12538313	Number of Non-Space Characters	int l=0; \n        string s; \n        Console.WriteLine("Enter Paragraph: "); \n        s = Console.ReadLine(); \n\n        l = s.Replace(" ", String.Empty).Length; \n        Console.WriteLine("Your Paragraph Length is: " + l); \n        Console.ReadLine();	0
4343298	4343178	Show tooltip for a button when text is too long	if (button1.Text.Length > Your button text length to be checked)\n{\n    System.Windows.Forms.ToolTip ToolTip1 = new System.Windows.Forms.ToolTip();\n    ToolTip1.SetToolTip(this.button1, this.button1.Text);\n}	0
21490191	21411654	Find Cell HeaderName in openXML	foreach (var cell in wsRow)\n{\n    // code to get the header cell\n    var header = ws.Cell(1, cell.Column);\n\n    // rest of your code here\n    // ...\n}	0
25546882	25545512	Adding checkbox with postback dynamically in gridview column	cbActive.CheckedChanged += SelectCheckBox_OnCheckedChanged	0
7493575	7493553	Finding standard deviation/variance in data values	// ... code from above\ndouble averageMaximumX = query.Average(t => double.Parse(t.XMax)); \ndouble varianceMaximumX = query.Sum(t => \n                Math.Pow(double.Parse(t.XMax) - averageMaximumX, 2)));\n\ndouble stdDevMaximumX = Math.Sqrt(varianceMaximumX);\nvarianceMaximumX /= query.Count();	0
18221395	18217432	How to show item in dropdownlist as being selected when we have corresponding datatextfield from gridview selected row	ddEquipmentName.SelectedIndex = ddEquipmentName.Items.IndexOf(ddEquipmentName.Items.FindByText(selectRow.Cells[2].Text));	0
5893553	5893523	C#: DateTime convert	DateTime parsed = DateTime.ParseExact("18/04/2011 4:57:20 PM", \n                                      "dd/MM/yyyy h:mm:ss tt", \n                                      CultureInfo.InvariantCulture);	0
23758491	23758374	how to extract those elements from the list which have square bracket in c#	var OuterBrackets_List= lst.Where(s => s.StartsWith("[") && s.EndsWith("]");\nvar AlphaNumeric_List = lst.Except(OuterBrackets_List);	0
24535001	24512084	Programmatically setting the 'Connect as' user in IIS7 using C#	ServerManager iisManager = new ServerManager()\n                        site = iisManager.Sites.FirstOrDefault(a => a.Name.Contains("Default"));\n                        site.VirtualDirectoryDefaults.Password = tbImpersonatorPassword.Text;\n                        site.VirtualDirectoryDefaults.UserName = tbImpersonatorUser.Text;	0
3648455	3648386	WPF app has no "Pin to Taskbar" option	For your MsiShortcutProperty table, add the following values to the table:\n\nColumns/values:\nMsiShortcutProperty/AppIDProperty\nShortcut_/MyShortcut.<guid>\nPropertyKey/System.AppUserModel.ID\nPropVariantValue/<YourCompanyName.ProductName.SubProduct.VersionInformation>	0
10823030	10823014	Assigning attributes from resx Files	[Required(ErrorMessageResourceName= "FullNameRequired", ErrorMessageResourceType = typeof(MyResource)]	0
32465579	32465136	How to pass stored procedure info to other routine c#	private DataSet CreateCommand(string procedureName, string[,] parameters)\n{\n    SqlCommand cmd = new SqlCommand();\n    cmd.CommandText = "EXECUTE " + procedureName;\n\n    for (int i = 0; i < parameters.Length; i++)\n    {\n        cmd.CommandText += " " + parameters[i, 0] + " = @" + parameters[i, 0];\n        cmd.Parameters.AddWithValue("@" + parameters[i, 0], parameters[i, 1]);\n    }\n\n    SqlDataAdapter da = new SqlDataAdapter();\n    DataSet ds = new DataSet();\n\n    da.SelectCommand = cmd;\n    da.Fill(ds);\n\n    return ds;\n}	0
22249380	22247609	inserting splitted text to ms access?	string[] splittedText1 = textBox2.Text.Split(' ');\nstring[] splittedText2 = textBox1.Text.Split(' ');\nstring[] splittedText3 = textBox3.Text.Split(' ');\n\nstring _sql = "Insert into [sales] ([productname], productquantity, productprice) VALUES (?,?,?)";\nOleDbCommand CmdSql = new OleDbCommand();\nCmdSql.Connection = Cnn;\n\nCmdSql.Parameters.Add("@productname", OleDbType.VarChar);\nCmdSql.Parameters.Add("@productquantity", OleDbType.VarChar);\nCmdSql.Parameters.Add("@productprice", OleDbType.VarChar);\n\ndecimal dQty = 0m;\ndecimal dPrice = 0m;\nfor (int i = 0; i < splittedText1.Length; i++)\n{\n    Decimal.TryParse(splittedText2[i], out dQty);\n    Decimal.TryParse(splittedText3[i], out dPrice);\n    CmdSql.Parameters["@productname"].Value = splittedText1[i];\n    CmdSql.Parameters["@productquantity"].Value = dQty;\n    CmdSql.Parameters["@productprice"].Value = dPrice;\n    CmdSql.ExecuteNonQuery();\n}	0
13402109	13401870	remove tailing zeros in decimal	decimal d = 12.45600m;\nd.ToString("0.#####");	0
23589804	23589555	Make exe file of app from another app	var p = new Process();\np.StartInfo.FileName = @"c:\Windows\Microsoft.NET\Framework64\v4.0.30319\csc.exe";\np.StartInfo.Arguments = @"c:\aa\Test.cs";\np.Start();	0
1539299	1539292	How events like CancelEventArgs can be used?	foreach (CancelEventHandler subHandler in handler.GetInvocationList())\n{\n     // treat individually\n}	0
11413095	11413048	Encrypt the password string in web.config	aspnet_regiis.exe	0
8748854	8748733	Lambda expression using Join for something more than a simple key	from a in tableA\nfrom b in tableB\nwhere a >= b.minX && a <= b.maxX\nselect a;	0
15690298	15689989	connecting api controller with service layer	public class RoleApiController : ApiController\n{\n    private RoleService _roleService = new RoleService();\n\n    public RoleUser GetRoleUser(int sectionID)\n    {\n        if (sectionID != null)\n        {\n            return _roleService.GetUsers(sectionID);\n        }\n        throw new HttpResponseException(HttpStatusCode.NotFound);\n    }\n}	0
24237734	24237664	Associated Properties: How to Avoid an Infinite Loop	private int width;\nprivate int height;\nprivate int length;\nprivate bool constrained;\n...\n\npublic int Width\n{\n    get { return width; }\n    set\n    {\n        width = value;\n        if (constrained)\n        {\n            height = value;\n            length = value;\n        }\n    }\n}	0
12399216	12399196	How to get current selected node (TREEVIEW)?	treeView1.SelectedNode.Name	0
11548830	11522181	Highlighting the selection in a RichEditBox	Windows.UI.Text.ITextSelection selection = richEditBox.Document.Selection;\n selection.StartPosition = 0;\n selection.EndPosition = n;	0
20741695	20703786	How to create a file in WCF service application in windows	string path = AppDomain.CurrentDomain.BaseDirectory;\nString dir = Path.GetDirectoryName(path);\ndir += "\\Emp_data";\nstring filename = dir+"\\Json_data.json";\nif (!Directory.Exists(dir))\n    Directory.CreateDirectory(dir); // inside the if statement\nFileStream fs = File.Open(filename,FileMode.OpenOrCreate, FileAccess.ReadWrite);\nStreamReader reader = new StreamReader(fs);	0
19726450	19726276	Check the value of a string passed in from an external source	List<string> answervalue=new List<string>;\nanswervalue.ADD("firstthing")\nanswervalue.ADD("secondthing")????\n\nif(answervalue.contains(/*the message value being send it*/)\n{\n//do some thing\n}	0
8719318	8719268	HTML File with xml and xmln declaration cannot be transformed	using System;\nusing System.IO;\nusing System.Xml;\nusing System.Xml.Xsl;\nusing System.Xml.XPath;\n\npublic class TransformXML\n{\n    //This will transform xml document using xslt and produce result xml document\n    //and display it\n\n    public static void Main(string[] args)\n    {\n        try\n        {\n            XPathDocument myXPathDocument = new XPathDocument(sourceDoc);\n            XslTransform myXslTransform = new XslTransform();\n            XmlTextWriter writer = new XmlTextWriter(resultDoc, null);\n            myXslTransform.Load(xsltDoc);\n            myXslTransform.Transform(myXPathDocument, null, writer);\n            writer.Close();\n            StreamReader stream = new StreamReader (resultDoc);\n            Console.Write("**This is result document**\n\n");\n            Console.Write(stream.ReadToEnd());\n        }\n        catch (Exception e)\n        {\n            Console.WriteLine ("Exception: {0}", e.ToString());\n        }\n    }\n}	0
31502247	31502138	After define ComboBox with ReadOnly = true i still can use my controller	myComboBox.IsEditable = false; // enables or disables editing of the text in text box of the ComboBox\nmyComboBox.IsHitTestVisible = false; // whether this element can possibly be returned as a hit test result from some portion of its rendered content.\nmyComboBox.Focusable = false; // indicates whether the element can receive focus.	0
10806440	10806397	Execute SQL Server stored procedure with input parameter	EXEC GetFilmsInCategory 'SF'	0
7596782	7596747	C# - How to list the files in a sub-directory fast, optimised way	public IEnumerable<string> GetAllFiles(string rootDirectory)\n{\n    foreach(var directory in Directory.GetDirectories(\n                                            rootDirectory, \n                                            "*", \n                                            SearchOption.AllDirectories))\n    {\n        foreach(var file in Directory.GetFiles(directory))\n        {\n            yield return file;\n        }\n    }\n}	0
16259171	16258835	Unable to access directory from FileSystemEventArgs.FullPath, wrong directory name	folderWatcher.Renamed += FolderWatcherOnRenamed;\n\nprivate static void FolderWatcherOnRenamed(object sender, RenamedEventArgs e)\n{\n\n    var attr = File.GetAttributes(e.FullPath);\n\n    if (attr == FileAttributes.Directory && e.OldName == "New Folder")\n    {\n\n        StartMonitoringDir(e.FullPath)\n    }\n}	0
8281137	8278491	Strange behavior with NUnit, ExpectedException & yield return	public IEnumerable<ImportField> CreateFields(HttpPostedFileBase file)\n    {\n        if (file == null) throw new ArgumentNullException("file");\n\n        return ExtractFromFile(file);\n    }\n\n    private IEnumerable<ImportField> ExtractFromFile(HttpPostedFileBase file)\n    {\n        using (var reader = new StreamReader(file.InputStream))\n        {\n            var firstLine = reader.ReadLine();\n            var columns = firstLine.Split(new[] { ',' });\n\n            for (var i = 0; i < columns.Length; i++)\n            {\n                yield return new ImportField(columns[i], i);\n            }\n        }\n    }	0
11214395	11213789	Is there a straightforward way to combine successive string values representing 15-minute blocks of time?	string[] times = { "07:00", "07:15", "07:30", "07:45", "08:00", "08:15", "08:30", "09:00", "09:15", "09:30", "09:45", "10:00", "10:15", "10:30", "11:15" };\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        DateTime prevDt = new DateTime(1);\n        string prevString = "";\n\n        StringBuilder output = new StringBuilder("UserXyz Deleted ");\n        foreach (string time in times)\n        {\n\n            DateTime dt = DateTime.ParseExact(time,"hh:mm", CultureInfo.InvariantCulture);\n            if (dt.Subtract(prevDt).TotalMinutes > 15)\n            {\n                if (prevString != "")\n                    output.Append(" " + prevString + ",");\n                output.Append(" " + time + " -");\n            }\n            prevString = time;\n            prevDt = dt;\n        }\n        output.Remove(output.Length - 1, 1);\n        MessageBox.Show(output.ToString());\n    }	0
18945288	18943923	Checkbox in wpf listview header not checking all items	class Song\n{\n  prop IsSelected\n  {\n    get { return this.selected; }\n    set { this.selected = value; PropertyChanged("IsSelected"); }\n  }\n}	0
13030612	13030414	open a page in IE using c#	var IE = new SHDocVw.InternetExplorer();\nobject URL = "http://www.northwindtraders.com";\n\nIE.ToolBar = 0;\nIE.StatusBar = false;\nIE.MenuBar = false;\nIE.Width = 622;\nIE.Height = 582;\nIE.Visible = true;\n\nIE.Navigate2(ref URL);	0
9153301	9153181	Adding a body to a HttpWebRequest that is being used with the azure service mgmt api	byte[] buf = Encoding.UTF8.GetBytes(xml);\n\nrequest.Method = "POST";\nrequest.ContentType = "text/xml";\nrequest.ContentLength = buf.Length;\nrequest.GetRequestStream().Write(buf, 0, buf.Length);\n\nvar HttpWebResponse = (HttpWebResponse)request.GetResponse();	0
13874856	13856352	Getting a Stream from a resource file / content	StorageFile storageFile =\n      await Windows.Storage.StorageFile.GetFileFromApplicationUriAsync(uri);\n\n    var randomAccessStream = await storageFile.OpenReadAsync();\n    Stream stream = randomAccessStream.AsStreamForRead();	0
8840761	8840619	How do I create a small button with three dots on it?	Button.Text = "?";	0
2023565	2023528	C#, Pass Array As Function Parameters	using System;\nusing System.Reflection;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n        public Int32 Add(Int32 a, Int32 b) { return a + b; }\n        static void Main(string[] args)\n        {\n            Program obj = new Program();\n\n            MethodInfo m = obj.GetType().GetMethod("Add");\n            Int32 result = (Int32)m.Invoke(obj, new Object[] { 1, 2 });\n        }\n    }\n}	0
22232263	22231789	Regex - loop through matches	var entry = "<key n=1>xzsd:test <sk id=1 hi=1>test <tag1>.............</tag1> <tag2>.............</tag2> ................ </sk> <sk id=2>test2 <tag1>.............</tag1> <tag2>.............</tag2> ................ </sk> </key>";\n\n        string pattern = "<key .*?>(.*)</key>";\n        Match match = Regex.Match(entry, pattern);\n        while (match.Success)\n        {\n            Console.WriteLine("Found: {0}",\n                              match.Groups[1].Value); //find only what is in (.*)\n            match = match.NextMatch();\n        }	0
3256314	3256276	How do I attach an id to a ListViewItem?	var data = List.SelectedItem as SongData;\nif (data != null)\n    ...	0
28275892	28238495	Getting Type of expression which stored in string	using System;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\n\npublic Type GetExpressionType(string expression, IDictionary<string, Type> variables)\n{\n  var types = new List<ParameterExpression>();\n  foreach (var varType in variables)\n    types.Add(Expression.Parameter(varType.Value, varType.Key));\n  var lamda = System.Linq.Dynamic.DynamicExpression.ParseLambda(types.ToArray(), null, expression);\n  return lamda.ReturnType;\n}	0
13370118	13369961	Trying to get the last part of a URL with Regex	string s = "http://www.s3.locabal.com/whatever/bucket/folder/guid";\n\n// Uri\nnew Uri(s).Segments.Last();\n\n// string\ns.Substring(s.LastIndexOf("/") + 1);\n\n// RegExp\nRegex.Match(s, ".*/([^/]+*)$").Groups[1];	0
22298978	20321264	How to Stop Catching a Specific Exception in C#	Label1.Text=(Excel.Worksheet1.Cells[1,1].value ?? "Some_Str";\nLabel2.Text=(Excel.Worksheet1.Cells[1,2].value ?? "Some_Str";\nLabel3.Text=(Excel.Worksheet1.Cells[1,3].value ?? "Some_Str";\nLabel4.Text=(Excel.Worksheet1.Cells[1,4].value ?? "Some_Str";	0
7023384	6976730	MS chart radar axis frequency	chart1.Series["Default"].ChartType = SeriesChartType.Polar;\nchart1.Series[0]["PolarDrawingStyle"] = "Line";\n// setup the X grid\nchart1.ChartAreas["Default"].AxisX.MajorGrid.Enabled = true;\nchart1.ChartAreas["Default"].AxisX.MajorGrid.IntervalType = DateTimeIntervalType.Hours;\nchart1.ChartAreas["Default"].AxisX.MajorGrid.Interval = 1;\nchart1.ChartAreas["Default"].AxisX.Crossing = 0;\n// setupthe Y grid\nchart1.ChartAreas["Default"].AxisY.MajorGrid.Enabled = true;	0
15943070	15942827	How does this overload resolution make any sense?	Console.WriteLine( \n   ((ICollection<KeyValuePair<object, object>) d2).\n      Remove(new KeyValuePair<object, object>("1", 2)));	0
21243655	21243403	How to use DbGeography.Filter in Linq with Entity Framework 5?	var point = DbGeography.FromText(string.Format("POINT({1} {0})", latitude, longitude), 4326);\n  var query = from person in persons\n              let region = point.Buffer(radius)\n              where SqlSpatialFunctions.Filter(person.Location, region) == true\n              select person;	0
4578313	4578169	How to use svcutil to generate client proxies for 2 separate services?	svcutil.exe /language:cs /out:GeneratedProxy.cs /config:app.config net.tcp://localhost:8000/ http://localhost:8005	0
15003858	14972713	Converting cartesian coordinates to latitude/longitude in Geographical Data	INSERT INTO SpatialTable (GeogCol1)\nVALUES (geography::STGeomFromText('POINT(122 47)', 4121));	0
25668571	25668289	How to store longitude and latitude while keeping decimal places?	decimal longitude = 0;\ndecimal latitude = 0;\nvar precision = BitConverter.GetBytes(decimal.GetBits(argument)[3])[2];	0
1525471	1525445	How do you tell the C# compiler that a symbol is a type and not a variable when they share the same name?	global::	0
1838768	1838687	C# - Can a List<MyClass> be seemlessly cast to a List<Interface> or similar?	List<IEntity>	0
26461550	26461394	How to send byteArray from android to wcf through ksoap2	SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);\nrequest.addProperty("source", bmpArray);\nSoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);\nnew MarshalBase64().register(envelope);\nenvelope.dotNet = true;\nenvelope.setOutputSoapObject(request);\nHttpTransportSE androidHttpTransport = new HttpTransportSE(URL, 300000);	0
5115031	5114571	What's best performance way to constantly change image on WP7?	using(MemoryStream stream = new MemoryStream( data ))\n{\n  BitmapImage image = new BitmapImage( );\n  image.SetSource( stream );\n}	0
1552404	1552392	Determine Genuine Windows Installation in C#	Win32 API	0
16160083	16148191	Rearrange Order number column of DataGridView after user sorting one of its columns?	private void dataGridView1_Sorted(object sender, System.EventArgs e)\n    {\n        foreach (DataGridViewRow dataGridViewRow in\n                                 dataGridView1.Rows.Cast<DataGridViewRow>())\n        {\n            dataGridViewRow.Cells["Order"].Value = dataGridViewRow.Index + 1;\n        }\n    }	0
1558009	1557989	Send mail using localhost SMTP	SmtpClient smtpClient = new SmtpClient();\nsmtpClient.UseDefaultCredentials = true;\nsmtpClient.Send(mailMessage);	0
10561670	10559187	Retrieve Json from service and pass to ApiController	public HttpResponseMessage Get()\n{\n    var resp = new HttpResponseMessage()\n    {\n        Content = new StringContent("{json here...}")\n    };\n    resp.Content.Headers.ContentType = \n                  new MediaTypeHeaderValue("application/json");\n    return resp;\n}	0
2326471	2326436	Adding XML Files to the Build	XmlDocument document = new XmlDocument();\ndocument.Load("Resources/DefaultConfig.xml");	0
11703154	11684891	How to use ormlite with SQL Server and Mars?	using(var cnx = DbFactory.CreateConnection(Global.ConnectionString))\n            {\n                using (var multi = cnx.QueryMultiple("mySchema.myStoredProc", new { communityId, categoryId }, commandType: CommandType.StoredProcedure))\n                {\n                    var projectMembers = multi.Read<ProjectMember>().ToList();\n                    var projects = multi.Read<Project>().ToList();\n                    BindProjectMembers(projects, projectMembers);\n\n                    return projects;\n                }\n            }	0
22640188	21552239	Getting parent node in Irony parser	Stack<ParseTreeNode> stack = new Stack { yourRootTreeNode };\nwhile(!stack.Empty)\n{\n   var current = stack.Pop();\n   if(current.ChildNodes != null)\n   {\n     if(current.ChildNodes.Contains(yourChildNode))\n        return current; /*parent of yourChildNode */\n\n     foreach(var child in current.ChildNodes)\n       stack.Push(child);\n\n   }\n}	0
25698983	25698961	How to check the modify time of a remote file	...\nvar request = WebRequest.Create(uri);\nrequest.Method = "HEAD";\n...	0
6061697	6061658	Group By Multiple Columns - LINQ	var groupedRows1 = from row in enumerableRowCollection\n                            group row by new { Network = row["NETWORK"], Week = row["Week"] };	0
13476071	13475999	In MVC3, how to set a nullable property of a Model in vb.Net?	public property MyProperty As Nullable(Of Integer)	0
2668341	2664806	How to detect Javascript pop-up notifications in WatiN?	frame.Button(Find.ByName("go")).ClickNoWait();\n\nSystem.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();\nstopwatch.Start();\n\nwhile (stopwatch.Elapsed.TotalMilliseconds < 3000d)\n{\n    if (alertDialogHandler.Exists())\n    {\n        // Do whatever I want to do when there is an alert box.\n        alertDialogHandler.OKButton.Click();\n        break;\n    }\n}	0
19978196	19977212	How do I set a list to null in C#?	[XmlArray("dependencies"), XmlArrayItem("dependency")]\n    public List<string> Dependencies { get; set; }\n    public bool ShouldSerializeDependencies()\n    {\n        if (Dependencies != null && Dependencies.Count > 0)\n        {\n            return true;\n        }\n        else\n        {\n            return false;\n        }\n    }	0
3403392	3403120	How do I truncate a file X bytes from the end?	FileStream.SetLength()	0
23173667	23173624	opening a word file in browser using C#	return File(fs, "application/vnd.ms-word", "documentfile.doc");	0
9473744	9473713	Filtering nulls on grouping	int someNumber = (from a in TableA.col1 \n                   where a.DateUTC != null \n                   group a by a.DateUTC.Value.ToLocalTime().Date into g \n                   where TableA.col2 = Emp\n                   select g).Count();	0
8382558	8382468	C# how to add elements to a xml file	XmlDocument doc = new XmlDocument();\ndoc.Load(spath);\nXmlNode snippet = doc.CreateNode(XmlNodeType.Element, "Snippet", null);\n\nXmlAttribute att = doc.CreateAttribute("name");\natt.Value = name.Text;\nsnippet.Attributes.Append(att);\n\nXmlNode snippetCode = doc.CreateNode(XmlNodeType.Element, "SnippetCode", null);\nsnippetCode.InnerText = code.Text;\n\nsnippet.AppendChild(snippetCode);\n\ndoc.SelectSingleNode("//Snippets").AppendChild(snippet);	0
14351008	13332569	How to create certificate authority certificate with makecert?	makecert -n "CN=root signing authority" -cy authority -r -sv root.pvk root.cer	0
17379993	17372046	Convert List to Tree	/// <summary>\n/// Get list of all categories except current one as well as all it's child categories\n/// </summary>\n/// <param name="id">Current category id</param>\n/// <param name="categories">List of categories</param>\n/// <returns>List of categories</returns>\npublic static List<Category> CategoriesWithoutChildren(int id, List<Category> categories)\n{\n    var currentCategory = categories.Single(x => x.Id == id);\n    categories.Remove(currentCategory);\n\n    if (currentCategory.ChildCategories.Count > 0)\n    {\n        currentCategory.ChildCategories.ToList().ForEach(x =>\n        {\n            categories = CategoriesWithoutChildren(x.Id, categories);\n        });\n    }\n\n    return categories;\n}	0
28555460	28555416	Checking values of objects from root to desired child	var value = root?.InnerObject2?.InnerObject2?.InnerObject3?.value;\nif(value != null)\n    stringBuilder.Append(value);	0
13779147	13778724	'System.DateTime' is not a valid Windows Runtime parameter type	public DateTimeOffset Calculate(DateTimeOffset dateTime) {\n    // etc..\n}	0
21227170	21227115	Linq: CONTAINS with multiple dynamic input string values	string[] selectedList = selected.Split(',');\nvar q = from a in dt.AsEnumerable()\n        where a.Field<string>("Period") == "Jan 2014" && \n        selectedList.Contains(a.Field<string>("Division")) \n        select a;\n\nGridView1.DataSource = q.CopyToDataTable();\nGridView1.DataBind();	0
1142893	1142828	Add timer to a Windows Forms application	private void Form1_Load(object sender, EventArgs e)\n    {\n        Timer MyTimer = new Timer();\n        MyTimer.Interval = (45 * 60 * 1000); // 45 mins\n        MyTimer.Tick += new EventHandler(MyTimer_Tick);\n        MyTimer.Start();\n    }\n\n    private void MyTimer_Tick(object sender, EventArgs e)\n    {\n        MessageBox.Show("The form will now be closed.", "Time Elapsed");\n        this.Close();\n    }	0
19480860	19480837	Converting 3-dimensional byte array to a single byte array	byte[,,] threeD = new byte[X,Y,Z];\nbyte[] res = new byte[X*Y*Z];\nint pos = 0;\nfor (int x = 0 ; x != X ; x++)\n    for (int y = 0 ; y != Y ; y++)\n        for (int z = 0 ; z != Z ; z++)\n            res[pos++] = threeD[x,y,z];	0
5404374	5402597	Can multiple classes share a single db table in ActiveRecord/NHibernate	interface IPerson\n{\n    string FirstName { get; set; }\n    string LastName { get; set; }\n}\n\ninterface IAddress\n{\n    string AddressLine1 { get; set; }\n    string AddressLine2 { get; set; }\n    string City { get; set; }\n    string Province { get; set; }\n    string Country { get; set; }\n}\n\nclass CustomerRecord : IPerson, IAddress // ActiveRecord object map to table...\n{  \n    // IPerson members...\n    public string FirstName { get; set; }\n    public string LastName { get; set; }\n\n    // IAddress members...\n    public string AddressLine1 { get; set; }\n    public string AddressLine2 { get; set; }\n    public string City { get; set; }\n    public string Province { get; set; }\n    public string Country { get; set; }\n}	0
20150642	20132703	Can you register a Web API ActionFilter without doing it globally?	GlobalConfiguration.Configuration.Filters.Add(new MyAttribute());	0
21548228	21546982	How to Save Pictures from MediaLibrary to IsolatedStorage	photoFilename = @"" + i.ToString() + p.Name.Substring(p.Name.LastIndexOf('.'));\nif (storage.FileExists(_photoPath + @"\" + _photoFilename))\n{\n    storage.DeleteFile(_photoPath + @"\" + _photoFilename);\n}\nusing (IsolatedStorageFileStream file = storage.CreateFile(_photoPath + @"\" + _photoFilename))\n    p.GetImage().CopyTo(file);	0
27399016	27398877	How to convert file to base64 UTF-8 little endian	var bytes = File.ReadAllBytes(@"file.wav");\nstring base64 = Convert.ToBase64String(bytes);	0
1397378	1397370	Getting Cross-thread operation not valid in MDIParent	if (InvokeRequired) \n    Invoke(new Action(MDIParent.MDIParentRef.BaseClose));\nelse\n    MDIParent.MDIParentRef.BaseClose();	0
4117275	4117256	How to retrieve width and height properties of an image from SQL Server?	System.Drawing.Image image = System.Drawing.Image.FromStream( \n    new System.IO.MemoryStream((byte[]) SqlReader["img_data"]) \n);\n\nint width = image.Width;\nint height = image.Height;	0
1499213	1479507	C# Xpath Query to find a single Node	XmlNamespaceManager mgr = new XmlNamespaceManager(m_xml.NameTable);\nmgr.AddNamespace("amzn", "http://s3.amazonaws.com/doc/2006-03-01/");\n\nXmlNodeList nodes = xmlDoc.SelectNodes("//amzn:Contents", mgr);	0
22633769	7310796	I would like to make an EditFor textbox accept numbers only	[RegularExpression("([1-9][0-9]*)", ErrorMessage = "Count must be a natural number")]\npublic int Count { get; set; }	0
29119184	29111441	How to generate properties in underlying class mapped to elements with x:Name attribute	ContentPresenter contentPresenter = FindVisualChild<ContentPresenter>(myListBox);\n\nDataTemplate yourDataTemplate = contentPresenter.ContentTemplate;\n\nTextBox txtName= yourDataTemplate.FindName("vidList", contentPresenter) \nas TextBox ;\nif (txtName!= null)\n{\n    // Do something with txtNamehere\n}	0
6493547	6492954	How to use ashx for html image defined in code behind?	img1.Attributes["src"] = "imageout.ashx?PageID=" + PageID.ToString() + "&DIImageID=" + DIImageID.ToString();	0
24566705	24566642	How to Press 3 Keys at a Time using KeyPress?	private bool isCtrlHPressed;\n\nprivate void txt_callerName_KeyDown(object sender, KeyEventArgs e)\n{\n    if (isCtrlHPressed && e.KeyCode == Keys.T && e.Modifiers == Keys.Control)\n        Console.WriteLine("^");\n\n    isCtrlHPressed = (e.KeyCode == Keys.H && e.Modifiers == Keys.Control);\n}	0
14841288	14840669	Upload events to Google API Calendar	EventEntry myEntry = new EventEntry();\nmyEntry.Title.Text = "Hello recurring Event!";\n// Set a location for the event.\nWhere eventLocation = new Where();\neventLocation.ValueString = "here and there";\nentry.Locations.Add(eventLocation);\n\n// Any other event properties\n\n// Recurring event:\nString recurData =\n  "DTSTART;VALUE=DATE:20070501\r\n" +\n  "DTEND;VALUE=DATE:20070502\r\n" +\n  "RRULE:FREQ=WEEKLY;BYDAY=Tu;UNTIL=20070904\r\n";\n\nRecurrence recurrence = new Recurrence();\nrecurrence.Value = recurData;\nmyEntry.Recurrence = recurrence;	0
14403421	14402930	Using a variable in the x y sort	public class YourDataClass {\n        public string RequestDate { get; set; }\n        public string NotifDate { get; set; }\n        .\n        .\n        .\n    }\n\n    public class Sorter<T> where T : YourDataClass {\n        private Dictionary<string, Func<T, T, int>> actions =\n            new Dictionary<string, Func<T, T, int>> {\n                {"reqDate", (x, y) => String.Compare(x.RequestDate, y.RequestDate)},\n                {"notifDate", (x, y) => String.Compare(x.NotifDate, y.NotifDate)}\n            };\n\n        public IEnumerable<T> Sort(IEnumerable<T> list, string howTo) {\n            var items = list.ToArray();\n            Array.Sort(items, (x, y) => actions[howTo](x, y));\n            return items;\n        }\n    }\n\n    public void Sample() {\n        var list = new List<YourDataClass>();\n        var sorter = new Sorter<YourDataClass>();\n        var sortedItems = sorter.Sort(list, "reqDate");\n    }	0
29519395	29519308	How to populate a SQL table column only the first time	string sSQL = @"UPDATE [MyTable1]\nSET AT09 = GETDATE()\n,AT80 = 'IP'\n,AT83 = 'CO'\n,AT34 = (CASE WHEN AT34 IS NULL THEN GETDATE() ELSE AT34 END)\n,AT84 = '" + sU + "' WHERE AS = 0";	0
2725097	2725055	How to compare a DateTime to a string	var dateTimeStr = "17:10:03";\nvar user_time = DateTime.Parse( dateTimeStr );\nvar time_now = DateTime.Now;\n\nif( time_now > user_time )\n{\n  // your code...\n}	0
14254876	14254805	Can I create a new array reference which contains a subset of an existing array, without copying memory?	ArraySegment<T>	0
13844444	13844022	Select only one column values from Excel	Worksheet sheet = (Worksheet)workBookIn.Sheets[sheetName];\nRange r =\n    sheet.get_range("B2", "B" + sheet.Cells.SpecialCells(XlCellType.xlCellTypeLastCell).Row);\nArray vals = pitch.Cells.Value;	0
5797391	5797248	In c#, Is it possible to loop through multiple collections of the same base type?	ArrayList list = new ArrayList();\nlist.AddRange( mApples );\nlist.AddRange( mBananas );\nlist.AddRange( mOranges );\n\nforeach( Fruit item in list )\n{\n    item.Slice();\n}	0
31680130	31672851	mouse position give wrong co-ordinates within group box	public Form1()\n{\n    InitializeComponent();\n\n    panel1.MouseMove += panel1_MouseMove;\n}\n\nvoid panel1_MouseMove(object sender, MouseEventArgs e)\n{\n    lbl.Location = e.Location;\n}	0
12270340	12265244	How to check a dataset belongs to another dataset	private int MatchFeeID(DataTable Dt)\n{\n  DataTable mainDt = bl.GetDataSet("Select * From FeeMaster"); //assume this is a function that will return all the fee structures from database.\n\n  var fids = (from row in mainDt.AsEnumerable().Distinct()\n            group row by row.Field<string>("fid") into rowGroup\n            select new\n            {\n              fid = rowGroup.Key\n            });\n\n  foreach (var fid in fids)\n  {\n    string id = fid.fid;\n\n    DataTable t1 = new DataTable();\n    DataTable t2 = new DataTable();\n\n    DataRow[] dr1 = mainDt.Select(String.Format("fid = '{0}'", id));\n\n    t1 = dr1.CopyToDataTable();\n    t2 = Dt;\n\n    bool res = TablesEqual(t1, t2, 0, 1);\n    if (res) return Convert.ToInt32(id);\n  }\n\n  return -1;\n}	0
10260007	10259982	Too fuzzy text WPF on XP	TextOptions.TextFormattingMode="Display"	0
4860566	4860531	Dynamically changing header text of a gridview column	protected void Button1_Click(object sender, EventArgs e)\n{\n    this.gvw1.Columns[0].HeaderText = "The new header";\n}	0
29576555	29576368	How to set the value of first input type text in document's first form using mshtml in C#?	private void button5_Click(object sender, EventArgs e)\n    {\n        var htmldoc = (HTMLDocument)webBrowser1.Document.DomDocument;\n        HTMLFormElement fm = (HTMLFormElement)htmldoc.forms.item(0);\n        foreach (IHTMLElement item in (IHTMLElementCollection)fm.all)\n        {\n            var textbox = item as IHTMLInputElement;\n            if (textbox != null)\n            {\n                textbox.value = "your text";\n            }\n        }\n    }	0
8197376	8197338	LINQ as a method parameter	this.DoSomething(tests.FirstOrDefault(x=>x.Name=="What I need to pass"))	0
16057750	16041780	Trying and failing to programmatically send mail using episerver mail	ISite site = (ISite)SiteHandler.Instance.CurrentSite;\nICategory category = EPiServerMailModule.Instance.GetSiteCategory(site);	0
489578	489071	When can an exception in a .NET WinForms app just get eaten without being caught or bubbling up to a windows exception?	static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)\n{\n     string b = null;\n     int i = b.Length;\n}	0
12507459	12507438	DateTime.ParseExact give the error: String was not recognized as a valid DateTime	var format = "dd/MM/yyyy hh:mm:ss";	0
25908676	25908582	How to run function that in packages in oracle (c#)	cmd.Parameters.Add("Return_Value", OracleDbType.Int16,\n        ParameterDirection.ReturnValue);	0
20062904	20062132	How to detect unhandled exceptions in Visual Studio?	/// <exception cref="SomeException">Some explanation</exception>	0
13676943	13665351	How to get browser name WCF Service	if (Request.Browser.Type.Contains("IE")) // replace with your check\n{\n    ...\n} \nelse if (Request.Browser.Type.ToUpper().Contains("Chrome")) // replace with your check\n{\n    if (Request.Browser.MajorVersion  < v1)\n    { \n        DoSomething(); \n    }\n    ...\n}\nelse { }	0
30870827	30870679	Paramaterized Query With SQL Data Reader C#	string myQuery = "Select [shoeSize] AS 'Shoe Size', [shoeBrand] AS 'Shoe Brand' FROM [myTable] "\n                 + "WHERE [customerName] = @customerName AND [customerPin] = @customerID"\n\n sqlCmd = new SqlCommand(myQuery, conn);\n sqlCmd.Connection.Open();\n sqlCmd.Parameters.AddWithValue("@customerName", customerName);\n sqlCmd.Parameters.AddWithValue("@customerID", customerID");\n --rest stays the same as before	0
10688777	10688727	Keep C# application running	public partial class DemoService : ServiceBase\n{\n    static void Main(string[] args)\n    {\n        DemoService service = new DemoService();\n\n        if (Environment.UserInteractive)\n        {\n            service.OnStart(args);\n            Console.WriteLine("Press any key to stop program");\n            Console.Read();\n            service.OnStop();\n        }\n        else\n        {\n            ServiceBase.Run(service);\n        }\n    }	0
271476	271149	listbox validation	for (int i = 0; i < lbSrc.Items.Count; i++)\n{\n    if (lbSrc.Items[i].Selected == true)\n    {\n        lbSrc.Items.RemoveAt(lbSrc.SelectedIndex);\n    }\n}	0
13309247	13309123	Is it bad practice to instantiate a Form from a UserControl?	MessageBox.Show()	0
19712718	18604749	How do you bind the DataTextField to a dictionary value using the key	...\n// set temporary the ID as a text\ncol.Text = item.OID.ToString();\nYourGrid.ItemDataBound += OnYourGridItemBound;\n...\nprivate static void OnYourGridItemBound(object sender, Telerik.Web.UI.GridItemEventArgs e)\n{\n    GridDataItem dataBoundItem = e.Item as GridDataItem;\n    if (dataBoundItem != null)\n    {\n        foreach (TableCell cell in dataBoundItem.Cells)\n        {\n            if (cell.Controls.Count > 0)\n            {\n                var link = cell.Controls[0] as HyperLink;\n                if (link != null)\n                {\n                    var dataItem = dataBoundItem.DataItem as MyClass;\n                    var id = link.Text;\n                    link.Text =                                     \n                       dataItem.AnotherObject[id].Person.FormattedName;\n                }\n            }\n        }\n    }\n}	0
23085346	23085092	Get ListView bound data on click event ASP.NET	protected void UpdateButton_Click(object sender, EventArgs e)\n{\n    if (e.CommandName == "Cancel")\n    {\n        ListViewDataItem lvd = (ListViewDataItem)((Control)e.CommandSource).NamingContainer;\n\n        //Same two lines for each value\n        Label ID = lvd.FindControl("idLabel") as Label;\n        string id = id.ToString();\n    }\n\n}	0
30566144	30565974	Check whether a string contain '&' character only	class Program\n    {\n        static void Main(string[] args)\n        {\n            char testChar = '&';\n            string test1 = "&";\n            string test2 = "&&&&&&&&&&";\n            string test3 = "&&&&&&&u&&&&&&&";\n\n            Console.WriteLine(checkIfOnly(testChar, test1)); // true\n            Console.WriteLine(checkIfOnly(testChar, test2)); // true\n            Console.WriteLine(checkIfOnly(testChar, test3)); // false\n            Console.WriteLine(checkIfOnly('u', test3));      // false\n            Console.WriteLine(checkIfOnly('u', "u"));      // true\n            Console.WriteLine(checkIfOnly('u', "uuuu"));      // true\n\n\n        }\n\n        static bool checkIfOnly(char testChar, string s)\n        {\n            foreach (char c in s)\n            {\n                if (c != testChar) return false;\n            }\n            return true;\n        }\n\n    }	0
532853	487499	How do I format the tooltip used by a DataGridView in virtual mode?	To use it with DataGridView create a ToolTip (HtmlToolTip) and add this after the InitalizeComponent() in your form to replace the default tooltip:\n\nSystem.Reflection.FieldInfo toolTipControlFieldInfo=\ntypeof(DataGridView).GetField("toolTipControl", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);\n\nSystem.Reflection.FieldInfo toolTipFieldInfo=\ntoolTipControlFieldInfo.FieldType.GetField("toolTip", System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.NonPublic);\n\nobject toolTipControlInstance =\ntoolTipControlFieldInfo.GetValue(myDataGridView);\n\ntoolTipFieldInfo.SetValue(toolTipControlInstance, myToolTip);	0
12638020	12637967	Cannot match exclusion of a character in Regular Expression when url Rewriting	(.*)courses\/(\w{4}\d{3})(?!\/)	0
8600893	8600825	How to show all hidden controls of a Form in C#?	public void MakeVisible(Control control)\n{\n    if(control.HasChildren)\n    {\n        foreach (Control child in control.Controls)\n        {\n            MakeVisible(child);\n        }\n    }\n    control.Visible = true;\n}	0
19270770	19264304	How to set log4net LockingModel programmatically after loading with XmlConfigurator?	var appender = log4net.LogManager.GetRepository()\n                                 .GetAppenders()\n                                 .OfType<FileAppender>()\n                                 .SingleOrDefault();\n\nif (appender != null)\n{\n     appender.LockingModel = new FileAppender.MinimalLock();\n}	0
2426778	2426733	Convert from VB.NET to C#	private double[] _PatchSpectrum = new double[49]\n\npublic double[] GetPatchSpectrum\n{\n    get { return _PatchSpectrum; }\n}\n\npublic double this[int index]\n{\n    set { this._PatchSpectrum[index] = value; }\n}	0
1793557	1793109	Using HashSets with ObservableCollection with WPF	public class ObservableHashSet<T> : ObservableCollection<T>  \n{ \n    protected override void InsertItem(int index, T item) \n    { \n        if (Contains(item)) \n        {\n            throw new ItemExistsException(item); \n        }\n        base.InsertItem(index, item); \n    } \n\n    protected override void SetItem(int index, T item) \n    { \n        int i = IndexOf(item); \n        if (i >= 0 && i != index)\n        {\n             throw new ItemExistsException(item); \n        }       \n        base.SetItem(index, item); \n    } \n}	0
7062970	7062929	Get latest version of tag from SVN	svn info	0
34355206	34354957	Show/hide ListBox Items on user action	public Interface IHidable\n{\n    bool hidden;\n}\n\npublic class MyModel : IHidable , ...\n{\n\n}\n\nprivate Collection<MyModel> realCoollection;  //use this for anything else\npublic Collection<IHidable > viewCollection  //Bind this in your WPF\n{\n  get {\n     Collection<IHidable>  resCollection = new Collection<IHidable>();\n     foreach (MyModel item in realCoollection)\n     {            \n        if (!item.hidden) res.Add((IHidable)item)\n     }\n     return resCollection;\n   }\n}	0
11619332	11619261	one long string => array/list<string> from text within quotes	var result = Regex.Matches(input, @"\"".+?\""")\n             .Cast<Match>()\n             .Select(m => m.Value)\n             .ToArray();	0
24765340	24765001	Retrieving the return value from Oracle with C#	cmdText = @"select PKG_RAP.add_resource(:projectView, :projectId, :workerId, :roleId) from dual";\nusing (var cmd = new OracleCommand(cmdText, conn))\nusing (cmd.Parameters.Add(":projectView", projectView))\nusing (cmd.Parameters.Add(":projectId", id))\nusing (cmd.Parameters.Add(":workerId", record["WORKERID"]))\nusing (cmd.Parameters.Add(":roleId", record["ROLEID"]))\nusing (var tx = conn.BeginTransaction()) {\n    try {\n        // resource ID\n        var resourceId = Convert.ToInt32(cmd.ExecuteScalar());\n        tx.Commit();\n        return resourceId;\n    } catch {\n        tx.Rollback();\n        throw;\n    }\n}	0
24074323	24074159	How to get OrderID to add new lines to the Order In SQL?	using (var connection = new SqlConnection("Your connection string"))\n{\n    int orderID;    \n    using (var command = new SqlCommand("INSERT INTO Orders (Created,OrderTotal) VALUES (GetDate(),@OrderTotal); SELECT CONVERT(int, SCOPE_IDENTITY()) as OrderID;", connection))\n    {\n        command.Parameters.AddWithValue("@OrderTotal", 10.0f);\n        connection.Open();\n        orderID = (int)command.ExecuteScalar();\n    }\n    //... now you can use orderID in your next query to insert an OrderLine\n}	0
7811484	7811424	Serialize Linq Results directly to JSON	var sb = from p in ent.people .........\nvar serializer = new JavaScriptSerializer();\nstring json = serializer.Serialize(sb);	0
2638878	2638831	check if a url has anything after the domain name	bool isRoot = new Uri("http://www.example.com").AbsolutePath == "/";	0
9564425	9564174	Convert byte array to image in wpf	private static BitmapImage LoadImage(byte[] imageData)\n    {\n        if (imageData == null || imageData.Length == 0) return null;\n        var image = new BitmapImage();\n        using (var mem = new MemoryStream(imageData))\n        {\n            mem.Position = 0;\n            image.BeginInit();\n            image.CreateOptions = BitmapCreateOptions.PreservePixelFormat;\n            image.CacheOption = BitmapCacheOption.OnLoad;\n            image.UriSource = null;\n            image.StreamSource = mem;\n            image.EndInit();\n        }\n        image.Freeze();\n        return image;\n    }	0
23592727	17021624	Passing a list of int to a HttpGet request	[HttpGet]\npublic int GetTotalItemsInArray([FromUri]int[] listOfIds)\n{\n       return listOfIds.Length;\n}	0
4002510	4002459	Trying to update SQL Server CE failing	string sql = "UPDATE SalesAssistant SET " \n+ "Name=@Name,IsEnabled=@IsEnabled,Role=@Role,LastModifiedDate=@LastModifiedDate,IsAdministrator=@IsAdministrator,PIN=@PIN,IsDeleted=@IsDeleted" + \n " WHERE SalesAssistantID=@SalesAssistantID";	0
8573485	8573422	Is it a good way to test value in property getters / setters of ConfigurationElement	if ((int)this["myproperty"] < 0 )\n{\n     return 0;\n}\n\nif ((int)this["myproperty"] > 999 )\n{\n     return 999;\n}\n\nreturn (int)this["myproperty"]	0
3140465	3140281	What data structure to use in my example	// assuming that the array is in row-major order...\npublic static bool IsInBorder(this BoardCell[,] board, int x, int y) {\n    return x == board.GetLowerBound(1) || x == board.GetUpperBound(1) ||\n           y == board.GetLowerBound(0) || y == board.GetUpperBound(0);\n}	0
23587903	23587862	How to get all elements into list or string with Selenium?	IList<IWebElement> all = driver.FindElements(By.ClassName("comments"));\n\nString[] allText = new String[all.Count];\nint i = 0;\nforeach (IWebElement element in all)\n{\n    allText[i++] = element.Text;\n}	0
8306369	8306158	C# How do I replace objects in one collection with Objects from another collection	foreach (var item in collection2.Take(20)) // grab replacement range\n{\n    int index;\n    if ((index = collection1.FindIndex(x => \n                                  x.Name == item.Name && \n                                  x.Description == item.Description)) > -1)\n    {\n        collection1[index] = item;\n    }\n}\ncollection1.AddRange(collection2.Skip(20)); // append the rest	0
16254835	16254808	Lamda Select passing extra parameter	view.Category = ctx.Categories.Select(x => CategoryMap.IndustryPage(x, industryID)).ToList();	0
18662694	18648438	Execute C++ function from C# application	[DllImport(@"GLZO.dll", CallingConvention = CallingConvention.Cdecl)]	0
22998166	22998127	Invoke Javascript file from C# application	var engine = new Jurassic.ScriptEngine();\nConsole.WriteLine(engine.Evaluate("5 * 10 + 2"));	0
27506648	27506476	DateTime convert to shortdatetime in grid	datagrid1.Columns[0].DefaultCellStyle.Format = "d";	0
24553974	24553072	Add pushpin to map from code behind in Windows Phone 8	MapLayer layer1 = new MapLayer();\nPushpin pushpin1 = new Pushpin();\npushpin1.GeoCoordinate = MyGeoPosition;\npushpin1.Content = "Content";\nMapOverlay overlay1 = new MapOverlay();\noverlay1.Content = pushpin1;\noverlay1.GeoCoordinate = MyGeoPosition;\nlayer1.Add(overlay1);\nmyMap.Layers.Add(layer1);	0
18767847	18767598	How to insert query to Excel by ODBC connection in ASP.NET?	string conStr = @"Driver={Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)};"+\n@"DBQ=|DataDirectory|\q.xlsx;ReadOnly=0;";	0
3494493	3494385	How to query the child elements of a particular parent element	var xml = XElement.Parse("your xml");\nvar q = from m in xml.Descendants("MIMIC")\n        where (int)m.Attribute("ID") == 1\n        from s in m.Descendants("SECTION")\n        select (string)s.Attribute("NAME");\n\nforeach ( var name in q ) {\n    Console.WriteLine(name);\n}	0
3975307	3975290	Produce a random number in a range using C#	Random r = new Random();\nint rInt = r.Next(0, 100); //for ints\nint range = 100;\ndouble rDouble = r.NextDouble()* range; //for doubles	0
2783598	2783584	Getting the list LocalAdmins for a set of Server	string hostName = "myComputer";\n        //get machine\n        using (DirectoryEntry machine = new DirectoryEntry("WinNT://" + hostName))\n        {\n            //get local admin group\n            using (DirectoryEntry group = machine.Children.Find("Administrators", "Group"))\n            {\n                //get all members of local admin group\n                object members = group.Invoke("Members", null);\n                foreach (object member in (IEnumerable)members)\n                {\n                    //get account name\n                    string accountName = new DirectoryEntry(member).Name;\n                    //DO SOMETHING...\n                }\n            }        \n        }	0
1942617	1942588	Where is DRV_QUERYFUNCTIONINSTANCEID declared?	#include <mmddk.h>	0
3913897	3912455	Need to display 2 diff banner sprites on same page based on the value of a control of Master Page	style="background-image:url(imagePathFromVarible)"	0
18786	18765	Importing C++ enumerations into C#	public enum eDeviceIntErrCodes \n    {\n        /// eDEVICEINT_ERR_FATAL -> 0x10001\n        eDEVICEINT_ERR_FATAL = 65537,\n    }	0
30501262	30501186	C# how to total counter ip in list	Dictionary<string, int> ips = new Dictionary<string, int>();\n\n// ...\n\nforeach (var info in tcpConnections)\n{\n    string list = info.LocalEndPoint.Address.ToString() + ":" + info.LocalEndPoint.Port.ToString();\n    string remote = info.RemoteEndPoint.Address.ToString() + ":" + info.RemoteEndPoint.Port.ToString();\n    if (list == serverMonitor)\n    {\n        if (ips.ContainsKey(remote))\n            ips[remote]++;\n        else \n            ips.Add(remote, 1);\n    }\n}\n\nforeach (var entry in ips)\n{\n    Console.WriteLine("{0} ({1})", entry.Key, entry.Value);\n}	0
12504707	12504562	How to extract a value of a http xml answer	using System.Xml;\n\npublic static void Main(String args[])\n{\n    XmlDocument foo = new XmlDocument();\n\n    //Let's assume that the IP of the target player is in args[1]\n    //This allows us to parameterize the Load method to reflect the IP address\n    //of the user per the OP's request\n    foo.Load( String.Format("http://freegeoip.net/xml/{0}",args[1])); \n\n    XmlNode root = foo.DocumentElement;\n\n    // you might need to tweak the XPath query below\n    XmlNode countryNameNode = root.SelectSingleNode("/Response/CountryName");\n\n    Console.WriteLine(countryNameNode.InnerText);\n}	0
2994453	2994419	Determine if string ends in whitespace	Char.IsWhiteSpace(myString[length - 1])	0
34422875	34422684	How can I get the string value of a checked item from a CheckedListBox?	DataRowView dr = checkedListBoxUnits.CheckedItems[0] as DataRowView;\nstring Name = dr["Unit"].ToString();	0
17991928	17984749	How to make the return call wait for async complete c#	public static async dbObj Login(String username, String password)\n    {\n        dbObj ret = new dbObj();\n        String rawWebReturn = "";\n        ret.propBag.Add(_BAGTYPE, returnTypes.Login.ToString());\n        DateTime date = DateTime.Now;\n        WebClient wc = new WebClient();\n        try\n        {\n            var result = await wc.DownloadStringTaskAsync(new Uri(baseLoginURI + "uname=" + username + "&pword=" + password + "&date=" + date.ToString()));\n            return parseWebReturn(result, ret);\n        }\n        catch (Exception e)\n        {\n            return parseWebReturn(e.Message, ret);\n        }\n    }	0
8578510	8578171	Query an xml file using linq to xml?	private string CountOfMales(XDocument doc, string locationToFilter)\n{\n  var selection = from customer in doc.Descendants("Customer")\n                 .Where(c => c.Attribute("Location").Value == locationToFilter)\n                 select new\n                 {\n                    MaleValue = customer.Element("Name").Attribute("Value").Value\n                 };\n\n                 return selection.FirstOrDefault().MaleValue;\n}	0
19757404	19756871	Loading images from listbox to picturebox	private void button1_Click(object sender, EventArgs e)\n    {\n        listBox1.Items.Clear();\n        DirectoryInfo dinfo = new DirectoryInfo(@"C:\cake");\n        FileInfo[] Files = dinfo.GetFiles("*.jpeg");\n        listBox1.Items.AddRange(Files);\n        listBox1.DisplayMember = "FileName";\n    }\n\n    private void listBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        if (listBox1.SelectedIndex != -1)\n        {\n            FileInfo fi = (FileInfo)listBox1.SelectedItem;\n            pictureBox1.ImageLocation = fi.FullName;\n        }\n    }	0
3256069	3253151	how to show price changes in sales report using t-sql	DECLARE @StartDate DATETIME ,\n    @EndDate DATETIME\n\nSELECT  @StartDate = '01 Jan 2010' ,\n        @EndDate = '15 Mar 2010'\n\nSELECT  [Products].pName AS ItemName,\n        SalesLog.[Price] AS Price ,\n        COUNT(*)AS Quantity ,\n        SUM(SalesLog.[Price]) AS Total\nFROM    SalesLog\n        JOIN [Products] ON [Products].pCode = SalesLog.ProductCode /*Check this join - I'm not sure what your relationship is*/\nWHERE   BillDate >= @StartDate\n        AND BillDate < @EndDate + 1\nGROUP BY [Products].pName ,\n        SalesLog.[Price]	0
12211841	12211562	How to activate control box of a disabled form?	private void  Form1_Load() \n    {\n       if(condition)\n       { \n          DisableControls();\n       }\n    }\n\n   private void DisableControls()\n   {\n        foreach(Control c in this.Controls)\n        { \n            // your disable code here.\n        }\n    }	0
2119643	2118833	Switching Database in LinqToSql	public static class DCHelper\n{\n  public static MyDataContext Create()\n  {\n     return new MyDataContext(ConfigurationManager.ConnectionStrings["CS"].ConnectionString);\n  }\n}	0
20518411	20517848	How does a delegate remember it's parameters?	public ModelView(Model model) : this()\n{\n    var closure = new AnonymousClass { _this = this, model = model };\n\n    Loaded += closure.Loaded;\n}\n\nprivate class AnonymousClass\n{\n    public ModelView _this;\n    public Model model;\n\n    public void Loaded(object sender, RoutedEventArgs e)\n    {\n        _this.DataContext = model;\n    }\n}	0
24090032	24089624	Replacing each instance of a word in a string with a unique value	var colors = new List<string> { "red", "green", "blue" };\nvar sentence = "The first car I saw was color, the second car was color and the third car was color";\nint i = 0;\nRegex.Replace(sentence, @"\bcolor\b", (m) => { return colors[i++ % colors.Count]; })	0
30619709	30619579	Autofac: How do you register a generic with multiple type arguments? Registering IGenRepo<T, TKey> with EFGenRepo<T, TKey>	RegisterGeneric(typeof(EFGenRepo<,>)).As(typeof(IGenRepo<,>));	0
11640479	11529014	Adding a Fix version using JIRA SOAP API	RemoteFieldValue v = new RemoteFieldValue\n{\n     id = "fixVersions",\n     values = new String[] { wi.Fields[29].Value.ToString() }\n};\nList<RemoteFieldValue> actionParams = new List<RemoteFieldValue>();\nactionParams.Add(v);\njiraSoapServiceService.updateIssue(token, key, actionParams.ToArray());	0
22478499	22478457	Remove From List X all content of List Y	z=s.Except(y).ToList();	0
18724528	18723695	Clean method in order to update collection in entity framework	var oldList = new List<ORDERS>();\nvar newList= new List<ORDERS>();\n\nvar IdsToRemove = oldList.Select(t => t.link_id).Except(newList.Select(t => t.link_id));\nvar IdsToAdd = newList.Select(t => t.link_id).Except(oldList.Select(t => t.link_id));\nvar IdsToUpdate =  newList.Select(t => t.link_id).Intersect(oldList.Select(t => t.link_id));\n\n//remove\nbdd.orders.where(x => IdsToRemove.Contains(x.link_id)).ForEach(x => bdd.Remove(x));\n//add\nforeach(var order in newList.Where(x -> IdsToAdd.Contains(x.link_id))\n{\n   bdd.Orders.Attach(order);\n   bdd.Entries(order).EntityState = EntityState.Added;\n}\n//update\nforeach(var order in newList.Where(x -> IdsToUpdate .Contains(x.link_id))\n{\n   bdd.Orders.Attach(order);\n   bdd.Entries(order).EntityState = EntityState.Modified;\n}\n\nbdd.SaveChanges();	0
18559738	18559721	I want to check if first column contains textbox1 and display full row in listview	SqlCommand cmd = new SqlCommand("SELECT c.CompanyName, o.Freight FROM Customers c INNER JOIN Orders o ON c.CustomerID = o.CustomerID WHERE c.CompanyName LIKE @recherche", cnn);\ncmd.Parameters.AddWithValue("@recherche", "%" + textBox1.Text + "%");	0
27641118	27640899	Styling text part in flow document	flowDocument1.Blocks.Paragraph.Text = "Here"	0
25061301	25060734	Make words from string matching with string bold	String term = "Gemini Oil";\nString input = "Gemini Sunflower Oil.";\nString result = Regex.Replace( input, String.Join("|", term.Split(' ')), @"<b>$&</b>");\nConsole.Out.WriteLine(result);\n\n\n<b>Gemini</b> Sunflower <b>Oil</b>.	0
4166502	4165377	Advanced sorting implementation in ASP.NET by letters, numbers & characters	using (SqlConnection cn = new SqlConnection(connectionString))\n{\n  using (SqlCommand cm = new SqlCommand(commandString, cn))\n  {\n     using (SqlDataReader dr = cm.ExecuteReader();\n     {\n        // use dr to read values.\n     }\n  }\n}	0
19090379	19090282	Protecting a file by a password	using (var zip = new ZipFile())\n{\n    zip.Password= "VerySecret!!";\n    zip.AddFile("test.txt");\n    zip.Save("Archive.zip"); \n}	0
13890458	13890231	I have a List with region of numbers and i want to build a List of all the numbers how can i do it?	List<string> list = new List<string>()\n{\n    "Test 0 Length 32 [41 - 73]",\n    "Test 1 Length 22 [81 - 103]"\n};\n\nvar numbers = \n   list.SelectMany(\n          s => Regex.Matches(s, @"\[(\d+)[ -]+(\d+)\]")\n               .Cast<Match>()\n               .Select(m => m.Groups.Cast<Group>().Skip(1).Select(x=>x.Value)\n                                                          .ToArray())\n               .Select(x => new {start=int.Parse(x[0]), end=int.Parse(x[1]) })\n               .SelectMany(x => Enumerable.Range(x.start, x.end- x.start + 1))\n        )\n       .ToList();	0
26760071	26759714	Upsert with composite key?	using (MyDbContext db = new MyDbContext())\n        {\n            foreach (var market in marketsList)\n            {\n                var existingMarket =\n                    db.Markets.FirstOrDefault(x => x.ProjectID == market.ProjectID && x.Year == market.Year);\n                if (existingMarket != null)\n                {\n                    //Set properties for existing market\n                     existingMarket.Year == market.Year\n                     //etc\n                }\n                else\n                {\n\n                    db.Markets.Add(market);\n                }\n                db.SaveChanges();\n            }\n        }	0
21756064	21754786	How to get a column value from data table with Linq	List<string> lstResult= (from table in dt.AsEnumerable()\n                                          where table.Field<int>("Id") == id\n                                          select table.Field<string>("status")).ToList();	0
17154539	12130059	How turn off pluralize table creation for Entity Framework 5?	modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();	0
4752709	4751799	Using MulticastDelegate as parameter while avoiding DynamicInvoke	public delegate void ObjectCreated(object sender, EventArgs args);\npublic delegate void ObjectDeleted(object sender, EventArgs args);\n\npublic event ObjectCreated ObjectWasCreated\n{\n    add\n    {\n        m_ObjectCreatedSubscribers.Add(value.Invoke);\n    }\n    remove\n    {\n        m_ObjectCreatedSubscribers.RemoveAll(e => e.Target.Equals(value));\n    }\n}\npublic event ObjectDeleted ObjectWasDeleted\n{\n    add\n    {\n        m_ObjectDeletedSubscribers.Add(value.Invoke);\n    }\n    remove\n    {\n        m_ObjectDeletedSubscribers.RemoveAll(e => e.Target.Equals(value));\n    }\n}\n\nprivate List<Action<object, EventArgs>> m_ObjectCreatedSubscribers = new List<Action<object, EventArgs>>();\nprivate List<Action<object, EventArgs>> m_ObjectDeletedSubscribers = new List<Action<object, EventArgs>>();\n\nvoid DispatchEvent(List<Action<object, EventArgs>> subscribers, object sender, EventArgs args)\n{\n    foreach (var subscriber in subscribers)\n        subscriber(sender, args);\n}	0
9232377	9232265	How to test if a MarshalByRefObject is valid?	Task task = new Task(() => { try { obj.Ping(); } catch {} });\ntask.Start();\nif(!task.Wait(1000)) throw new TimeoutException();\n// handle other task exceptions etc	0
1909164	1909127	How to bind c++ dll to my C# program - winCE	using System.Runtime.InteropServices; // DllImport\npublic class Win32 {\n  [DllImport("User32.Dll")]\n  public static extern void SetWindowText(int h, String s);\n}	0
31420122	31420045	How to give ADO.NET Parameters	string sql = "SELECT empSalary from employee where salary = @salary";\n SqlConnection connection = new SqlConnection(/* connection info */);\n SqlCommand command = new SqlCommand(sql, connection);\n\n command.Parameters.AddWithValue("salary", txtSalary.Text);	0
33662741	33617619	remote validation triggering multiple times	async:false	0
7836046	7835918	How to get the Names of all Columns in a Linq to Entity Datamodel (with one table)?	IEnumerable<FieldList> properties = from p in typeof(T).GetProperties()\n                                where (from a in p.GetCustomAttributes(false)\n                                where a is EdmScalarPropertyAttribute\n                                select true).FirstOrDefault()\n                                select new FieldList\n                                {\n                                   FieldName = p.Name,\n                                   FieldType = p.PropertyType,\n                                   FieldPK = p.GetCustomAttributes(false).Where(a => a is EdmScalarPropertyAttribute && ((EdmScalarPropertyAttribute)a).EntityKeyProperty).Count() > 0\n                                 };	0
19852282	19852084	C#, How to make function that order list as we need in parameter	public static List<someclass> OrderAsc(\n    List<someclass> object, \n    specific_field_by_someone )\n{\n    var data_table = new Dictionary<string, Func<someclass,object>>() \n    {\n        {"id", x => x.id },\n        {"name", x => x.name }\n    }\n\n    return object.OrderBy(data_dable["name"]);\n}	0
17482142	17482089	Is there such a thing as a "don't care" when constraining a generic parameter to another generic interface?	public T DefinitionPopulate<T, TD, DontCare>(IDataReader dr)\n    where T: class, new()\n    where TD: IEntityDefinition<T, DontCare>, new()	0
34010165	34007896	How can i change background of programmatically added button in C# Xamarin?	btn.SetBackgroundColor(Android.Graphics.Color.Yellow);	0
6688972	6619774	Using Regex.Match static method to find a match starting at a specific position	public static Match Match(string input, string pattern)\n{\n  return new Regex(pattern, RegexOptions.None, true).Match(input);\n}\n\npublic static Match Match(string input, string pattern, RegexOptions options)\n{\n  return new Regex(pattern, options, true).Match(input);\n}	0
295134	295125	LINQ: Get attribute with any namespace but specific name	elem.Attributes().FirstOrDefault(a=>a.Name.LocalName == "from");	0
2197078	1885151	Can I reattach or suspend a BindingExpression without warnings?	public void OnChangeClicked(object sender, RoutedEventArgs e)\n{\n    XmlDataProvider ds = Resources["testDS1"] as XmlDataProvider;\n    string xml = "<root><item>1</item></root>";\n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(xml);\n    using(ds.DeferRefresh())\n    {\n       ds.Document = doc;\n       ds.XmlNamespaceManager = new XmlNamespaceManager(doc.NameTable);\n    }\n}	0
24837466	24837359	How to retrieve n number of rows from DataTable through for loop	for (int i = 0; i < dt.Rows.Count; i++)\n{\nfor (int j = 0; j < dt.Columns.Count; j++)\n{\n    dt.Rows[i][j] = decrypted(dt.Rows[i][j].ToString());\n}\n}	0
242495	242478	Opening a file relative to server folder	string path = Server.MapPath("~");	0
21554444	21554284	Load xml file into 2d rectangular array using linq	double[][] array = \n   doc.Root.Elements("Month")\n      .Select(month => month.Elements().Select(x => (double)x).ToArray())\n      .ToArray();\n\nforeach(var innerArray in array)\n    Console.WriteLine(innerArray.Length); // you can get length of inner array	0
18739120	18739091	Is it possible to write a ROT13 in one line?	static string ROT13(string input)\n{\n    return !string.IsNullOrEmpty(input) ? new string (input.ToCharArray().Select(s =>  { return (char)(( s >= 97 && s <= 122 ) ? ( (s + 13 > 122 ) ? s - 13 : s + 13) : ( s >= 65 && s <= 90 ? (s + 13 > 90 ? s - 13 : s + 13) : s )); }).ToArray() ) : input;            \n}	0
814778	814712	VSTO - Outlook event handler in C#	private void mcAI_Open(ref bool Cancel)\n{\n    Cancel = true;\n}	0
10962843	10272365	Override two collection - pattern	interface IStudent {\n   string Name { get; set; }\n   List<Subjects> Marks  { get; set; }\n   int RollNumber  { get; set; }\n}\n\nclass EntityViewModel: IStudent {\n   IStudent FromExcel;  \n   IStudent FromDB;\n   public string Name {\n     get { return Choose("Name").Name; }\n     set { Choose("Name").Name = value; }\n   }\n   public string RollNumber{\n     get { return Choose("RollNumber").RollNumber; }\n     set { Choose("RollNumber").RollNumber = value; }\n   }\n   internal IStudent Choose(string propertyName){\n     if(IsOveridable(propertyName))\n        return this.FromExcel;\n     else \n        return this.FromDB  \n   }\n}\nclass ViewModel{\n   ObservableCollection<EntityViewModel> Entities;\n}	0
24526189	24526077	Manipulation specific string c#	string sIn = "%1111_?2222_?3333_";\nstring sOut = string.Join("_", sIn.Split('_').Where((x, index) => index != 1));	0
32576527	32576178	Is it possible to split a string into an array of strings and remove sections not between delimiters using String.Split or regex?	valuesCombined.Split(',').Select(s => s.Trim().Substring(1, s.Length - 2)).ToArray();	0
20266364	20247186	Unit testing WebApi routes with custom handlers	var routeDate = config.Routes.GetRouteData(request);	0
25308374	25305157	How to use a custom presenter in WPF?	public class Setup : MvxWpfSetup\n{\n    public Setup(Dispatcher dispatcher, IMvxWpfViewPresenter presenter)\n        : base(dispatcher, presenter)\n    {\n    }	0
7433344	7433000	Obfuscate Assembly and Reflection	[global::System.Reflection.Obfuscation(Exclude=true, Feature="renaming")]	0
3457032	3456926	How to insert a thousand separator (comma) with convert to double	... .ToString("#,##0.00")	0
20055841	20055549	C# server performance: how to exit foreach loop	string ServersToPing = "localhost:80 localhost:443";\nstring[] ServerArrays = ServersToPing.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);\n\nforeach (string server in ServerArrays)\n{\n    string host = server.Substring(0, server.IndexOf(':'));\n    Ping pingreq = new Ping();\n    PingReply pingrep = pingreq.Send(host, 30 * 1000);\n    Console.WriteLine("{0}:time={1}ms", pingrep.Address.ToString(), pingrep.RoundtripTime.ToString());\n}\n\nConsole.ReadLine();	0
12572054	12571984	MessageBox.Show makes DirectShow go	DoEvents()	0
12677896	12677799	In RowFilter, how To Select the all the Table Columns in C#?	private void txtSearch_TextChanged(object sender, EventArgs e)\n{\n    StringBuilder sb = new StringBuilder();\n\n    foreach (DataColumn column in dv.Table.Columns)\n    {\n        sb.AppendFormat("{0} Like '%{1}%' OR ", column.ColumnName, txtSearch.Text);\n    }\n\n    sb.Remove(sb.Length - 3, 3);\n    dv.RowFilter = sb.ToString();\n    dgClientMaster.DataSource = dv;\n}	0
1342660	1306985	How to Get Total Page Count for a Report Using CrystalReportViewer?	viewer.ShowLastPage();\n        string TotalPage = viewer.GetCurrentPageNumber().ToString();\n        viewer.ShowFirstPage(); \n        pageNo.Text = viewer.GetCurrentPageNumber() + " of " + TotalPage;	0
33480466	33480255	How can i have a case in a switch statement that lets a user input a string to be displayed	switch(choice)\n{\n   case 1: ...\n      .\n      .\n      .\n   case -1: Console.WriteLine("Put in your own saying: ");\n            phrase = " " + Console.ReadLine();\n            break;\n}	0
23100143	23100001	Ninject how to resolve dependency in one call	public void Main()\n{\n    Target sometarget = new Target();\n    IKernel kernel = new StandardKernel(new Bindings());\n    //var weapon = kernel.Get<IWeapon>();\n    var character = kernel.Get<Character>();\n    character.Attack(sometarget);\n}	0
5266242	5266207	C#: Split string and assign result to multiple string variables	public class MySplitter\n{\n     public MySplitter(string split)\n     {\n         var results = string.Split(',');\n         NamedPartA = results[0];\n         NamedpartB = results[1];\n     }\n\n     public string NamedPartA { get; private set; }\n     public string NamedPartB { get; private set; }\n}	0
12761705	12760970	Getting an IEnumerable from a port.DataReceived Event and its subscriber method?	SerialPort port;\nstring myReceivedLines;\n\n   protected override void SolveInstance(IGH_DataAccess DA)\n  {\n\n    string gcode = default(string);\n    DA.GetData(0, ref gcode);\n\n    port = new SerialPort(selectedportname, selectedbaudrate, Parity.None, 8, StopBits.One);\n    port.DtrEnable = true;   \n    port.Open();            \n    port.DataReceived += this.portdatareceived;\n\n    if (gcode == null)\n    {\n        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Specify a valid GCode");\n        return;\n    }\n    else\n    {\n        DA.SetDataList(0,  myReceivedLines);\n        port.WriteLine(gcode);\n    }    \n              }\n\n    private void portdatareceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)\n    {\n        myReceivedLines = port.ReadExisting();\n    }	0
31615419	31615344	Converting a database table into JSON stream	var obj = new MyRecord();\nvar json = new JavaScriptSerializer().Serialize(obj);	0
11667095	11666630	Local to GMT DateTime Conversion	String xmlDateString = XmlConvert.ToString(DateTime.UtcNow,XmlDateTimeSerializationMode.Local);	0
3943824	3943799	Deserializing an an array element	[XmlArray(ElementName = "Products")]\n[XmlArrayItem("Product")]\n    public MyProduct[] Products;	0
6287133	6286596	Fluent NHibernate pattern for both IHttpModule and console apps	public class PeopleRepository {\n    public PeopleRepository(ISession session) {\n        // store session\n    }\n}	0
1526334	1526315	developing and maintaining an application library developed in both Java and C#	public void testGetCrystallographicOrthogonalisation() {\n\n    double[] len = { 10.0, 11.0, 12.0 };\n    double[] ang = { 80.0, 90.0, 100.0 }; // degrees!\n    RealSquareMatrix m = RealSquareMatrix\n.getCrystallographicOrthogonalisation(len, ang);\n    RealSquareMatrix mm = new RealSquareMatrix(3, new double[] {\n9.843316493307713, 0.0, 0.0, -1.7632698070846495,\n10.832885283134289, 0.0, 0.0, 1.9101299543362344, 12.0 });\n    MatrixTest.assertEquals("orthogonalise", mm, m, 0.000000000001);\n}	0
11488404	11488260	How do you actually delete a database in VS?	using System.IO;\n\nnamespace MySQLCEApplication\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // Call the File class Delete method to delete the database.\n            File.Delete("Test.sdf");\n        }\n    }\n}	0
17592544	17591830	Reading XML Data and Storing in DataTable	using HtmlAgilityPack;\n\nclass Program\n{\n    static void Main(string[] args)\n    {\n        var doc = new HtmlDocument();\n        doc.Load("log.txt");\n        var dt = new DataTable();\n        bool hasColumns = false;\n        foreach (HtmlNode row in doc\n            .DocumentNode\n            .SelectNodes("//mainelement"))\n        {\n            if (!hasColumns)\n            {\n                hasColumns = true;\n                foreach (var column in row.ChildNodes\n                    .Where(node => node.GetType() == typeof(HtmlNode)))\n                {\n                    dt.Columns.Add(column.Name);\n                }\n            }\n            dt.Rows.Add(row.ChildNodes\n                .Where(node => node.GetType() == typeof(HtmlNode))\n                .Select(node => node.InnerText).ToArray());\n        }\n    }\n}	0
11522073	11507239	LINQ query result with string manipulation and regex	DashboardEntities dashboardDB = new DashboardEntities();\n\nvar sites = dashboardDB.Instances\n    .Select(attr => new SiteModel\n        {\n            url = attr.url,\n            server = attr.server,\n            pool = attr.pool,\n            version = attr.version,\n            client = attr.url\n        })\n    .ToList();\n\nsites.ForEach(attr => attr.client = Regex.Replace(attr.client, @"\.[a-z-./]+", "").Replace("formation-", ""));	0
16565306	16565241	Loop through a dictionary collection to search a key and increase value	if (Session["CurrCatId"] != null)\n{\n    CurrCatId = (int)(Session["CurrCatId"]);\n\n    // if the dictionary isn't even in Session yet then add it\n    if (Session["itemColl"] == null)\n    {\n        Session["itemColl"] = new Dictionary<int, int>();\n    }\n\n    // now we can safely pull it out every time\n    itemColl = (Dictionary<int, int>)Session["itemColl"];\n\n    // if the CurrCatId doesn't have a key yet, let's add it\n    // but with an initial value of zero\n    if (!itemColl.ContainsKey(CurrCatId))\n    {\n        itemColl.Add(CurrCatId, 0);\n    }\n\n    // now we can safely increment it\n    itemColl[CurrCatId]++;\n}	0
17855540	17855295	generate 4 digit unique identity key based on date	DateTime dt = new DateTime(2000,1,1);\nDateTime dtEnd = dt.AddDays(9999);\nConsole.WriteLine("Maximum date available:" + dtEnd.ToShortDateString());\n\ndtEnd = new DateTime(2013,7,25);\nTimeSpan ts = dtEnd - dt;\nConsole.WriteLine("Today Day number from base: " + ts.TotalDays);	0
16307224	16306253	how to convert time in string format into date time format using C#	string StartTime = ((TextBox)TestDV.FindControl("txtBST")).Text.ToString();\nDateTime dt = new DateTime();\ntry { dt = Convert.ToDateTime(StartTime); } \ncatch(FormatException) { dt = Convert.ToDateTime("12:00 AM"); }\nStartTime = dt.ToString("HH:mm");	0
30050881	28418066	Libdvbcsa, missing header files	-I/Users/bill/Desktop/libdvbcsa-master/src/dvbcsa	0
8293123	8292959	how to use one collection as a parameter to function call in another collection of the same size?	drivers.Select((d,i) => new { Index = i, Driver = d })\n       .ToList()\n       .ForEach(entry => car[entry.Index].AssignDriver(entry.Driver));	0
8697934	8697890	Display Text for Enum	enum MyEnum \n{ \n    [Description("This is black")] \n    Black, \n    [Description("This is white")] \n    White \n}	0
6473792	6471218	Lotus Notes - Saving Corrupt Attachment Programmatically - NotesEmbeddedObject	NotesEmbeddedObject.ExtractFile	0
6252053	6252024	How to cast to System.Timespan?	System.TimeSpan ts = (i.joinDt - DateTime.Now.Date).Value;	0
28450259	28433041	Filter Datagridview rows using TextBox	private void ChercheStextBox_TextChanged(object sender, EventArgs e)\n    {\n        var bd = (BindingSource)dataGridView3.DataSource;\n        var dt = (DataTable)bd.DataSource;\n        dt.DefaultView.RowFilter = string.Format("LibService like '%{0}%'", ChercheStextBox.Text.Trim().Replace("'", "''"));    \n        dataGridView3.Refresh();\n\n\n    }	0
24361513	24361187	How to add attribute and also elementString via XmlTextWriter?	myxml.WriteStartElement("site");\nmyxml.WriteAttributeString("isTrue", "false");\nmyxml.WriteString("http://www.example.com");	0
7301864	7301848	Is it possible to declare a type alias name in XAML?	public class Blobs : BlobCollection {}	0
25958012	25957920	passig data between activities xamarin	StartActivity (typeof (MainActivity)); };	0
1192690	1188125	Adding a cookie to web service port client	wsdl.exe	0
13462375	13462169	How to read from txtfile and then pass the information to another class c#	Person[] people= new Person[4];\nusing(var file = System.IO.File.OpenText(_LstFilename))\n{\n   int j=0;\n while (!file.EndOfStream)\n    {\n        String line = file.ReadLine();\n\n        // ignore empty lines\n        if (line.Length > 0)\n        {    \n\n            string[] words = line.Split(' ');\n             Person per= new Person(words[0], words[1], words[2], Convert.ToInt32(words[3]));\n\n             people[j]=per;\n             j++\n\n        }\n\n}	0
1647218	1643160	put wpf on a win hdl	public void CreateControl(IntPtr hParentWnd)\n  {\n    _userControl = new MyWPFUserControl();\n\n    var parameters = \n      new HwndSourceParameters("", _initialWidth, _initialHeight)\n      {\n        ParentWindow = (IntPtr)hwndParent,\n        WindowStyle = ...,          // Win32 style bits\n        ExtendedWindowStyle = ...,  // Win32 ex style bits\n      })\n\n    _hwndSource = \n      new HwndSource(parameters) { RootVisual = _userControl };\n  }\n\n  public void DestroyControl()\n  {\n    _hwndSource.Destroy();\n  }	0
23173563	23173471	Load my combobox with the column names of my database table	cmdReader = new MySqlCommand(query, conn);\nmyReader = cmdReader.ExecuteReader();\n\nfor(int index=0; index < reader.FieldCount; index++)\n{\n   c.Items.Add(myReader.GetName(index));\n}	0
5935644	5935601	read from file in c#	byte[] twoBytes = new byte[2];\nint bytesRead = fs.Read(twoBytes, 0, twoBytes.Length);	0
313799	252882	Get a list of members of a WinNT group	Public Function MembersOfGroup(ByVal GroupName As String) As List(Of DirectoryEntry)\n    Dim members As New List(Of DirectoryEntry)\n    Try\n        Using search As New DirectoryEntry("WinNT://./" & GroupName & ",group")\n            For Each member As Object In DirectCast(search.Invoke("Members"), IEnumerable)\n                Dim memberEntry As New DirectoryEntry(member)\n                members.Add(memberEntry)\n            Next\n        End Using\n    Catch ex As Exception\n        MessageBox.Show(ex.ToString)\n    End Try\n    Return members\nEnd Function	0
28225404	28220610	Redirect Controller to Another Controller	if (configurationCondition)\n{\n    routes.MapRoute("Hijaack",\n        url: "controllerA/{*theRest}",\n        defaults: new { controller = "controllerB", action = "Index" });\n}	0
17486961	17486799	Binding (and refreshing) a List<T> to a ListBox	private void FillItems()\n{\n    allItems = GetAllItems();\n    availableItems = new BindingList<string>(allItems);\n    selectedItems = new BindingList<string>();\n\n    itemsListBox.DataSource = availableItems;\n    selectedItemsListBox.DataSource = selectedItems;\n}\n\nprivate void addItemButton_Click(object sender, EventArgs e)\n{\n    object itemsToAdd = itemsListBox.SelectedItems;\n    foreach (string item in itemsToAdd) {\n        availableItems.Remove(item);\n        selectedItems.Add(item);\n    }\n}	0
22862955	22859544	Combinaison all cases k from n	public static void main(final String[] args) {\n    ArrayList<String> list = new ArrayList<>();\n    list.add("1");\n    list.add("2");\n    list.add("3");\n    list.add("4");\n    list.add("5");\n    List<String> result = getCombinations(list, 2);\n    System.out.println(result.size());\n    System.out.println(result);\n}\n\nprivate static List<String> getCombinations(final List<String> list, final int length) {\n    if (length >= 1) {\n        return removeUntilLength(list, length, 0);\n    }\n    return new ArrayList<>();\n}\n\nprivate static List<String> removeUntilLength(final List<String> list, final int length, final int lastIdx) {\n    List<String> ret = new ArrayList<>();\n    if (list.size() == length) {\n        ret.add(list.toString());\n    } else {\n        for (int i = lastIdx; i < list.size(); i++) {\n            List<String> tmp = new ArrayList<>(list);\n            tmp.remove(i);\n            ret.addAll(removeUntilLength(tmp, length, Math.max(i, 0)));\n        }\n    }\n    return ret;\n}	0
3637089	3632521	Collection with 10 elements (only)	public void SaveScore(ScoreInfo scoreInfo)\n    {\n        var listOfScoreInfo = this.GetListOrDefault<ScoreInfo>(App.SCORE);\n        bool isAdd = true;\n        foreach (var info in listOfScoreInfo)\n        {\n            if (info.Name == scoreInfo.Name && info.Score == scoreInfo.Score)\n                isAdd = false;\n        }\n        if(isAdd)\n            listOfScoreInfo.Add(scoreInfo);\n        listOfScoreInfo.Sort(scoreInfo.Compare);\n\n        if (listOfScoreInfo.Count > 15)\n        {\n            listOfScoreInfo.RemoveAt(15);\n        }\n\n        this.AddOrUpdateValue(App.SCORE, listOfScoreInfo);\n        this.Save();\n    }	0
18706843	18706538	Data layer as WCF vs an in app data layer	public Customer GetCustomer(int customerID)\n   {\n         return DataLayer.GetCustomer(customerID);\n   }	0
8182469	8167037	change password control validation	protected void ChangePassword1_ChangedPassword(object sender, EventArgs e)\n    {\n\n        if (ChangePassword1.CurrentPassword == ChangePassword1.NewPassword)\n        {\n            Response.Redirect("ChangePassword.aspx");\n\n        }\n        //Label1.Text = "current and new passwords should not match";        \n        Label1.Visible = false;\n    }	0
1666763	1666588	Rijndael algorithm (How to create our own Key )	var plainText = "This will be encrypted.";\nvar aesAlg = new RijndaelManaged();\naesAlg.Key = new byte[32] { 118, 123, 23, 17, 161, 152, 35, 68, 126, 213, 16, 115, 68, 217, 58, 108, 56, 218, 5, 78, 28, 128, 113, 208, 61, 56, 10, 87, 187, 162, 233, 38 };\naesAlg.IV = new byte[16] { 33, 241, 14, 16, 103, 18, 14, 248, 4, 54, 18, 5, 60, 76, 16, 191};\nICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);\n\nmsEncrypt = new MemoryStream();\nusing (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) {\n    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)) {\n        swEncrypt.Write(plainText);\n    }\n}\n\nreturn msEncrypt.ToArray();	0
502026	502021	How do I round a decimal to a specific fraction in C#?	Math.Round(n * 8) / 8.0	0
447702	447566	Unicode String in Hibernate Queries	IList<Person> people = session\n    .CreateQuery("from Person p where p.Name like :name")\n    .SetParameter("name", "%???%")\n    .List<Person>();	0
11759095	11758912	How to button_click function for dynamically created button column in datagridview	private void Form1_Load(object sender, EventArgs e)\n    {\n        dataGridView1.CellContentClick += new DataGridViewCellEventHandler(dataGridView1_CellContentClick);\n\n        DataGridViewButtonColumn select = new DataGridViewButtonColumn();\n        select.Text = "Details";\n        select.HeaderText = "Details";\n        select.Name = "Select";\n        dataGridView1.Columns.Add(select);\n    }\n\n    private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e)\n    {\n        if (e.ColumnIndex == dataGridView1.Columns["Select"].Index)\n        {\n            MessageBox.Show(String.Format("Clicked! Row: {0}", e.RowIndex));\n        }\n    }	0
34094391	34094232	Adding n amount of characters to ListBox	var aPlusses = string.Empty;\nfor(var i = 0; i < numA; i++)\n{\n    aPlusses += "+";\n}	0
4711697	4711580	Creating Webservice for retreiving value and updating it to database	public static void PrintSource(Uri address)	0
4224142	4223888	DataGridView - Shortcut Keys Vs MouseClick for Cell Focus	private void dataGridView1_KeyDown(object sender, KeyEventArgs e)\n {\n    if (e.KeyData == (Keys.Alt | Keys.S))\n    {\n         //put your code to validate i.e. what u are trying in button click event\n    }\n }	0
28259827	28247624	DeletedRowInaccessibleException while doing for each	var bRows = dataset.TableB.Where(r => r.RowState != DataRowState.Delete);\nvar results = (from rowA in dataset.TableA\n               join rowB in bRows\n                    on rowA.ID equals rowB.ID\n               join rowC in dataset.TableC\n                    on rowB.ID equals rowC.ID\n               select new { rowB.ColA, rowC.ColA });	0
20071450	20070843	C# verify file certificate	try\n  {\n  X509Certificate theSigner = X509Certificate.CreateFromSignedFile("c:\\r\\1.dll");\n  Console.Write("certificate info :"+ theSigner.GetCertHashString());\n  }\n  catch (Exception ex)\n  {\n         Console.WriteLine("No digital signature ");\n\n\n  }	0
9476337	9398278	How should I create a custom graphical console/terminal on Windows?	deque<string>	0
13220105	13219936	how can i launch an application page when alarm give notification in windows phone 7?	//Create a reminder\nReminder myReminder = new Reminder("buy milk");\nmyReminder.Title = "Buy Milk";\nmyReminder.Content = "Don't forget to buy milk!";\nmyReminder.BeginTime = DateTime.Now.AddSeconds(10);\nmyReminder.ExpirationTime = DateTime.Now.AddSeconds(15);\nmyReminder.RecurrenceType = RecurrenceInterval.None;\nmyReminder.NavigationUri = new Uri("/MainPage.xaml?fromReminder=1",         UriKind.Relative);\n\n//Add the reminder to the ScheduledActionService\nScheduledActionService.Add(myReminder);	0
5286768	5286495	Abstract away a compound identity value for use in business logic?	IEquatable<T>	0
25275672	25275548	Is there a way to select two parts of an array and use both at the same time?	var BDATE = "08/12/2014";\nstring[] strArr = BDATE.Split('/');\n\nfields.SetField("txt_Date_Of_Birth", \n    string.Format("{0}-{1}-XXXX", strArr[0], strArr[1]));	0
18110483	18083982	How to query GetMonitorBrightness from C#	ManagementScope scope;\n SelectQuery query;\n\n scope = new ManagementScope("root\\WMI");\n query = new SelectQuery("SELECT * FROM WmiMonitorBrightness");\n\n using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))\n {\n    using (ManagementObjectCollection objectCollection = searcher.Get())\n    {\n      foreach (ManagementObject mObj in objectCollection)\n      {\n        Console.WriteLine(mObj.ClassPath);\n        foreach (var item in mObj.Properties)\n        {\n          Console.WriteLine(item.Name + " " +item.Value.ToString());\n          if(item.Name =="CurrentBrightness")\n            //Do something with CurrentBrightness\n        }\n      }\n    }\n  }	0
6909360	6524501	Custom X/Y grid line in MSChart control	double low_med = 17; // was 30\ndouble med_hi = 92;  // was 70\n\n// Set Y axis custom labels\naxisY.CustomLabels.Add(0, low_med, "Low");\naxisY.CustomLabels.Add(low_med, med_hi, "Medium");\naxisY.CustomLabels.Add(med_hi, 100, "High");\n\nStripLine stripLow = new StripLine();\nstripLow.IntervalOffset = 0;\nstripLow.StripWidth = low_med;\nstripLow.BackColor = Color.FromArgb(64, Color.Green);\n\nStripLine stripMed = new StripLine();\nstripMed.IntervalOffset = low_med;\nstripMed.StripWidth = med_hi - low_med;\nstripMed.BackColor = Color.FromArgb(64, Color.Orange);\n\nStripLine stripHigh = new StripLine();\nstripHigh.IntervalOffset = med_hi;\nstripHigh.StripWidth = 100 - med_hi;\nstripHigh.BackColor = Color.FromArgb(64, Color.Red);\n\naxisY.StripLines.Add(stripLow);\naxisY.StripLines.Add(stripMed);\naxisY.StripLines.Add(stripHigh);	0
3876844	3859719	ObjectDataSource filtering on date/time in SPGridView	BoundField.DataField	0
22076775	22076375	How to clear WebBrowser control in WPF	if (wb != null)\n{\n    if (e.NewValue != null)\n        wb.NavigateToString(e.NewValue as string);\n    else\n        wb.Navigate("about:blank");\n}	0
15446807	15446032	Populating List with binary search	public void button1_Click(object sender)\n{\n    List<string> files = listBoxFiles.Items.OfType<string>().ToList();\n    string key = textBoxFileToSearch.Text;\n    backgroundWorkerSearch.RunWorkerAsync(new Tupple<List<string>,string>(files, key));\n}\n\nvoid backgroundWorkerSearch_DoWork(object sender, DoWorkEventArgs e)\n{\n     var state = e.Argument as Tupple<List<string>,string>;\n     List<string> files = state.Item1;\n     string key = state.Item2;\n     // You can now access the needed data.\n     List<string> searchResult = new List<string>();\n     // ...\n     e.Result = searchResult;\n}\n\nvoid backgroundWorkerSearch_RunWorkerCompleted(RunWorkerCompletedEventArgs e)\n{\n     List<string> searchResult = e.Result;\n     // Show result in the UI thread.\n}	0
19073168	19073093	Is in possible to do everything with goto's?	// i = 0\nIL_0001: ldc.i4.0                  // Load integer value 0 to stack\nIL_0002: stloc.0   // i            // Store stack value in local variable 0\n\n// goto loop-condition\nIL_0003: br.s      IL_0009         // Jump to IL_0009\n\n// loop-start:\n// i = i + 1\nIL_0005: ldloc.0   // i            // Load variable 0 to stack\nIL_0006: ldc.i4.1                  // Load integer `1` to stack\nIL_0007: add                       // Add top two stack values\nIL_0008: stloc.0   // i            // Store result in local variable 0\n\n// loop-condition:\n// if (i < 10) { goto loop-start }\nIL_0009: ldloc.0   // i            // Load variable 0 to stack\nIL_000A: ldc.i4.s  0A              // Load integer `10` to stack\nIL_000C: clt                       // Compare top two stack values\nIL_000E: stloc.1   // CS$4$0000    // Store stack value in local variable 1\nIL_000F: ldloc.1   // CS$4$0000    // Load variable 1 to stack\nIL_0010: brtrue.s  IL_0005         // Jump to IL_0005 if stack value is true	0
2906063	2906022	TimeSpan to ISO8601 duration format string	TimeSpan timeSpan = new TimeSpan(0, value, 0);\n   return XmlConvert.ToString(timeSpan);	0
3551320	3551283	Parse Simple DateTime	DateTime dt = DateTime.ParseExact("1122010".PadLeft(8, '0'), "MMddyyyy", System.Globalization.CultureInfo.CurrentCulture);	0
27937899	27937823	Fill ComboBox with data from SQL Server	SqlDataAdapter da = new SqlDataAdapter("SELECT ItemName FROM TBItemList", oSqlConn);\nDataTable dt = new DataTable();\nda.Fill(dt);\ncbxparameter.DataSource = dt;\ncbxparameter.DisplayMember = "ItemName";\ncbxparameter.ValueMember = "ItemName";	0
33653361	33652932	Best approach to pass database context from controller to model	public class AccountController : Controller\n{\n   private IRepository<Account> _accountRepository;\n\n   public AccountController(IRepository<Account> accountRepository)\n   {\n      this._accountRepository = accountRepository;\n   }\n}	0
6244079	6243942	how to send an email with an attachment from C#?	var client = new SmtpClient("smtp.gmail.com", 587)\n        {\n            Credentials = new NetworkCredential("username", "password"),\n            EnableSsl =true\n        };\n\n        client.Send(message);	0
15865968	15865797	C# Add value to array through user input	namespace ConsoleApplication1\n{\n    class Program\n    {\n        static int[] Item; //Fixed int Item[] to int[] Item\n        static void Main(string[] args)\n        {\n            Add(3);\n            Add(4);\n            Add(6);\n        }\n\n\n     public static void Add(int x){\n\n         if (Item == null)  // First time need to initialize your variable\n         {\n             Item = new int[1];\n         }\n         else\n         {\n             Array.Resize<int>(ref Item, Item.Length + 1);\n         }\n         Item[Item.Length-1] = x; //fixed Item.Length -> Item.Length-1\n     }\n\n    }\n}	0
6551810	6551782	how to get control id in loop to upload 4 file in a single loop?	FileUpload[] uploads = { FileUpload1, FileUpload2, ... };	0
13384261	13384003	Sorting and deleting slides using Open XML SDK	SlidePart slidePart = presentationPart.GetPartById(slideRelId) as SlidePart;	0
1991552	1991496	Header in richtext format and manipulating the rtf file	{\rtf1\ansi\ansicpg1252\deff0\deflang1030{\fonttbl{\f0\fswiss\fcharset0 Arial;}}\n{\*\generator Msftedit 5.41.21.2509;}\viewkind4\uc1\pard\f0\fs20 Hello,\par\n\b world\b0 !\par\n}	0
5658484	5658453	C#: How to replace \\ with \	string temp = @"\\h\\k";\ntemp = temp.Replace(@"\\", @"\");	0
11390723	11390697	Get property value by string	var properties = typeof(Setting);\nforeach (var prop in properties)\n{\n    // here you can access the name of the property using prop.Name\n    // if you want to access the value you could use the prop.GetValue method\n}	0
33787782	33787708	How do I use byte constants as switch cases in C#?	public const byte CONNECT = 100;	0
11205523	11203849	How to get single new line in a Rich Text Box to appear as single-spaced	rtx_report.AppendText(lclFileInfo.pathOnly + "\r");	0
6324247	6323917	How do I construct a LINQ with multiple GroupBys?	var output = from mt in MemberTanks\n             group by {mt.Tier, mt.Class, mt.TankName} into g\n             select new { g.Key.Tier, \n                          g.Key.Class, \n                          g.Key.TankName, \n                          Fights = g.Sum(mt => mt.Battles), \n                          Wins = g.Sum(mt=> mt.Victories\n                        };	0
12553279	11682075	Button Click Inside ListView in Monoandriod	public class CustomListAdapter: BaseAdapter {\n    public CustomListAdapter(Context context, EventHandler buttonClickHandler) {\n        _context = context;\n        _buttonClickHandler = buttonClickHandler;\n    }\n\n    public View GetView(int position, View convertView, View parent) {\n        var itemView = convertView;\n\n        if(itemView == null) {\n            var layoutInflater = (LayoutInflater)_context.GetSystemService(Context.LayoutInflaterService);\n            itemView = layoutInflater(Resource.Layout.ItemView);\n        }\n\n        var button = itemView.FindViewById<Button>(Resource.Id.MyButton);\n        button.Click += _buttonClickHandler;\n    }\n\n    // ... Rest of the code omitted for simplicity.\n}	0
9942128	9941897	Get Index of Current TabPage of PageControl	var index = tabcontrolname.GetActiveTabIndex();	0
5106125	5105592	Change only the DataValueField of a Listbox?	dimension.DataSource = provider.DimensionList.Select(d=>new {Id=d.Id,Text=d.ToString()}).ToList();\ndimension.DataValueField = "Id";\ndimension.DataTextField = "Text";\ndimension.DataBind();	0
16906137	16905892	Replace string in string list with string list	List<string> list1 = new List<string>() { "item1", "item2" };\nlist1 = list1.SelectMany(x => x == "item2" ? new[] { "item3", "item4" } \n                                            : new[] { x })\n             .ToList();	0
1863114	1841176	Invoke callback in Moq	class MockGetRightsProxy : IGetRightsProxy\n{\n    public void GetRights(EventHandler<GetRightsCompletedEventArgs> callback)\n    {\n        // Create some args here\n        GetRightsCompletedEventArgs args = new GetRightsCompletedEventArgs(\n            new object[] { new ObservableCollection<Right>() }, null, false, null);\n\n        callback(null, args);\n    }\n\n}	0
22985872	22985292	c# Remove string from XML	string s = @"<z:row ID=""1""\n   Author=""2;#Bruce, Banner""\n   Editor=""1;#Bruce, Banner""\n   FileRef=""1;#Reports/Pipeline Tracker Report.xltm"" \n   FileDirRef=""1;#Reports"" \n   Last_x0020_Modified=""1;#2014-04-04 12:05:56"" \n   Created_x0020_Date=""1;#2014-04-04 11:36:21"" \n   File_x0020_Size=""1;#311815""\n    />";\n\nstring result = Regex.Replace(s,"\"([0-9];#)","");	0
10379715	10379464	Alphanumeric to numeric only	return new string(str.Where(char.IsDigit).ToArray());	0
757011	756939	lambda expression to verify list is correctly ordered	public static bool IsOrdered<T>(this IEnumerable<T> source)\n{\n  var comparer = Comparer<T>.Default;\n  T previous = default(T);\n  bool first = true;\n\n  foreach (T element in source)\n  {\n      if (!first && comparer.Compare(previous, element) > 0)\n      {\n          return false;\n      }\n      first = false;\n      previous = element;\n  }\n  return true;\n}	0
21813194	21812286	DataGridView show row on bottom	DataGridView.DisplayedRowCount()	0
31565695	31565355	Spawning Player at certain Point in Unity	levelManager.LoadLevel (SceneName)	0
1293642	1293582	C#, XmlDoc: How to reference method overloads	/// Has a close relation to the <see cref="Get(string)"/>  \n/// and <see cref="Get(int)" /> methods.	0
14965386	14962285	How rotate a 3D cube at its center XNA?	var rotationCenter = new Vector3(0.5f, 0.5f, 0.5f);\n\nMatrix transformation = Matrix.CreateTranslation(-rotationCenter)\n    * Matrix.CreateScale(scaling) \n    * Matrix.CreateRotationY(rotation) \n    * Matrix.CreateTranslation(position);	0
24226492	23988916	how can i use TotalRow to show summary in Janus gridex?	grd.TotalRow = Janus.Windows.GridEX.InheritableBoolean.True;\ngrd.RootTable.Columns[10].AggregateFunction = Janus.Windows.GridEX.AggregateFunction.Sum;	0
12154497	12154287	Insert Record into two tables with one to many relation by using linq to ado.net entity froamwork	try \n{\n  // create objects, set properties ...\n  PersonalInfo myRecipient = new PersonalInfo();\n  myRecipient.FirstName = id_firstName.ToString(); // CHECK if value is valid (correct max length, ..)\n  // and so on ..\n\n  // set reference from Entity Department to Recipient\n  myDepartment.PersonalInfo = myRecipient;\n\n  myDB.AddToPersonalInfoes(myRecipient);\n  myDB.AddToDepartments(myDepartment);\n  myDB.SaveChanges();\n} \ncatch (Exception ex)\n{\n  Debug.WriteLine(ex.Message);\n  if (ex.InnerException!=null)\n    Debug.WriteLine(ex.InnerException.Message);\n}	0
19870746	19601043	How do I Run PowerShell command in windows form application?	PowerShell ps = PowerShell.Create();\n\n        PSCommand cmd1 = new PSCommand();\n        cmd1.AddCommand("Import-Module");\n        cmd1.AddParameter("activedirectory");\n        ps.Commands = cmd1;\n        ps.Invoke();\n\n        cmd1.AddCommand("Add-PSSnapin");\n        cmd1.AddParameter("Name", "Quest.ActiveRoles.ADManagement");\n        ps.Commands = cmd1;\n        ps.Invoke();\n\n        cmd1.AddCommand("Get-QADMemberOf");\n        cmd1.AddParameter("identity", "rpimentel");\n        cmd1.AddCommand("where-object");\n        ScriptBlock filter = ScriptBlock.Create("$_.Name -ne 'Domain Users'");\n        cmd1.AddParameter("FilterScript", filter);\n        cmd1.AddCommand("Add-QADGroupmember");\n        cmd1.AddParameter("Member", "ktest");\n        ps.Commands = cmd1;\n        ps.Invoke();	0
25041498	25041367	Exclude Fields while saving document in mongodb in c#	class student\n{\n   int rollnol;\n   string name;\n\n   [BsonIgnore]\n   string fees;\n}	0
12712817	12712158	Converting UTF-8 to UTF-16BE	using(var writer = \n    new StreamWriter(fileName, new Encoding.UnicodeEncoding(true,true,true))\n{\n   writer.Write(editorTextString);\n}	0
12630488	12630347	Searching the first few characters of every word within a string in C#	if(str.StartsWith("Cal") || str.Contains(" Cal")){\n    //do something\n}	0
25667792	25667723	How can I assign a Func<> using the conditional ternary operator?	var filter = (someBooleanExpressionHere)\n   ? new Func<Something, bool>(x => x.SomeProp < 5)\n   : x => x.SomeProp >= 5;	0
8582668	8582087	FormView Data Binding	protected void DisplayPayOut(object sender, EventArgs e)\n{\n    Label Payout = FormView1.FindControl("PayoutLabel") as Label;\n    object dataItem = DataBinder.GetDataItem(FormView1);\n    Payout.Text = DataBinder.Eval(dataItem, "field1NameHere").ToString() + DataBinder.Eval(dataItem, "field2Namehere").ToString();\n}	0
7330672	7330526	Using generics for caching in the Entity Framework	OfType<T>	0
4428224	4428183	Concatenate a Dictionary to a string of "key=val&key=val..."	var entries = NavigationContext.QueryString.Select\n      (x => Uri.EscapeDataString(x.Key) + "=" + Uri.EscapeDataString(x.Value));\n\nstring joined = string.Join("&", entries.ToArray());	0
22771255	22771148	Check string for characters, without getting hung up on spaces	if(! Regex.IsMatch(myString, @"^\s*\d(\d|\s)*$")) { ... }	0
16998467	16998447	Set custom BackgroundColor of a Excel sheet cell using epplus c#	Color colFromHex = System.Drawing.ColorTranslator.FromHtml("#B7DEE8");\nws.Cells["A1:B1"].Style.Fill.BackgroundColor.SetColor(colFromHex);	0
33471359	33471142	C# App hangs during failed SqlConnection	//Put these two lines to where you want to check the connection\nThread checkConnection = new Thread(() => checkConn());\ncheckConnection.Start();\n\n//Then create a method like below\npublic void checkConn()\n{\n     //Call the check connection method here\n     if(!miconexion(ip, user, pass))\n     {\n         //Handle failure here, please use Invoke if you want to control the UI thread.\n     }\n     //For best resource usage, join the thread after using it.\n     Thead.Join();\n}	0
2387364	2387322	Automatically close windows explorer	foreach (Process p in Process.GetProcessesByName("explorer"))\n{\n   p.Kill();\n}	0
5089742	5088896	Form has minimum size after restoring from minimize state	private void Form1_FormClosing(object sender, FormClosingEventArgs e)\n{\n   Properties.Settings.Default.Size = this.Size;\n   Properties.Settings.Default.Location = this.Location;\n   Properties.Settings.Default.Save();\n}\n\nprivate void Form1_Load(object sender, EventArgs e)\n{\n   this.Size = Properties.Settings.Default.Size;\n   this.Location = Properties.Settings.Default.Location;\n}	0
20619302	20618869	How to make file path from stream for class or method that need to use it	\\host\file	0
10270109	10270022	C#: generate RANDOM numbers between two limits IN ORDER	public static double[] GenerateRandomOrderedNumbers(double lowerBoundInclusive, double upperBoundExclusive, int count, Random random = null)\n{\n    random = random ?? new Random();\n    return Enumerable.Range(0, count)\n        .Select(i => random.NextDouble() * (upperBoundExclusive - lowerBoundInclusive) + lowerBoundInclusive)\n        .OrderBy(d => d)\n        .ToArray();\n}	0
2316051	2311683	unable to edit DataGridView populated with results of LINQ query	string testXML =\n        @"<p><entry>\n          <author>TestAuthor1</author>\n          <msg>TestMsg1</msg>  \n          </entry></p>\n        ";\n\nXElement xmlDoc = XElement.Parse(testXML);\n\nvar query = from entry in xmlDoc.Descendants("entry")\n            select new MergeEntry\n            {\n                author = entry.Element("author").Value,\n                message = entry.Element("msg").Value,\n            }; //You were missing the ";" in your post, I am assuming that was a typo.\n\n//I first binded to a List, that worked fine. I then changed it to use a BindingList\n//to support two-way binding.\nvar queryAsList = new BindingList<MergeEntry>(query.ToList());\n\nbindingSource1.DataSource = queryAsList;\ndataGridView1.DataSource = bindingSource1;	0
18261006	18260969	How to bind to a public class function in wpf	public string MiniButtonText\n{\n   get\n   {\n       return GameInfo.IsMiniInserted == Visibility.Visible ? "Remove Mini" : "Insert Mini";\n   }\n}	0
15677517	15677017	How to scroll ListView in a touchscreen	ScrollViewer.PanningMode	0
5494983	5494974	Convert 1D array index to 2D array index	p.x = index / 3;\np.y = index % 3;	0
26732204	26716724	How to prevent NHibernate ISession to change connection after every query execution?	ISession dummy = factory.OpenSession();\n\nusing (ISession session = factory.OpenSession(dummy.Connection))\n{\n// my stuff here. the connection will remain the same across multiple query executions\n}	0
6552842	6528527	Gridview edit value	protected void gvData_PreRender(object sender, EventArgs e)\n{\n    if (this.gvData.EditIndex != -1)\n    {\n        TextBox tb = new TextBox();\n\n        for (int i = 0; i < gvData.Rows[gvData.EditIndex].Cells.Count; i++)\n            try\n            {\n                tb = (TextBox)\n                    gvData.Rows[gvData.EditIndex].Cells[i].Controls[0];\n\n                if (tb.Text.Length >= 30)\n                {\n                    tb.TextMode = TextBoxMode.MultiLine;\n                }\n            }\n            catch { }\n    }\n}	0
7049092	7049057	Accessing TextBox inside a ContextMenu	ContextMenu cm = ItemList.Resources["listBoxItemContextMenu"] as ContextMenu;\nMenuItem mi = cm.Items[0] as MenuItem;\nTextBox tb = mi.Items[0] as TextBox;	0
2656403	2656332	What most efficient method to find a that triangle which contains the given point?	if (y' > (y * x') / x)\n{\n    // center triangle\n}\nelse\n{\n    // right triangle\n}	0
28025826	28025275	How to invert the y coordinate of a 4x4 matrix?	finalMatrix = finalMatrix * Matrix.Reflection(new Plane(0,-1,0, 0));	0
19118458	19109423	Convert specific attribute value in a JSON object to IEnumerable in C#	private IEnumerable<string> GetAllNames(string json)\n{\n    JObject jo = JObject.Parse(json);\n    return jo["students"].Select(s => s["name"].ToString());\n}	0
4070502	4070455	How to avoid all code nodes to expand on project opening?	TextEditor->C#->Formatting->Advanced	0
4694667	4694457	Easiest way to pass parameters to Crystal Report from C#?	private readonly CrystalReportViewer reportViewer = new CrystalReportViewer();\n...\n    crystalReport.Load(this.reportViewer.ReportSource.ToString());\n\n    crystalReport.SetParameterValue("customerId", customerId);\n    crystalReport.SetParameterValue("isCurrent", isCurrent);\n    crystalReport.SetParameterValue("TotalSales", totalSales);	0
2253960	2253890	How to wrap a very long word	word-wrap: break-word	0
27800398	27800353	json.net serialization/deserialization on an external json file	var json = File.ReadAllText(filename);\nvar stats = JsonConvert.DeserializeObject<Dictionary<string, dynamic>>(json);	0
16914014	16913928	Get a specific value in an xml document with c#	var doc = XDocument.Parse(xml); //use XDocument.Load if you have path to a file\n\nstring minSell = doc.Descendants("sell")\n                    .First()\n                    .Element("min")\n                    .Value;\n\nConsole.WriteLine(minSell); //prints 166.22	0
25797409	25797301	Use a Task to avoid multiple calls to expensive operation and to cache its result	lock(StaticObject) // Create a static object so there is only one value defined for this routine\n{\n    if(_getDataTask == null)\n    {\n         // Get data code here\n    }\n    return _getDataTask\n}	0
30128750	30128400	Checking the equality of two NTAccount objects	accessRule.IdentityReference.Translate(typeof(SecurityIdentifier)) == serviceUserAccount.Translate(typeof(SecurityIdentifier))	0
4713125	4711922	EF4 - Get Child Value	context.Windows.Local.SingleOrDefault(w => w.Id == idWindow);	0
809570	809545	How to TOP, ORDER BY and DISTINCT in the same query with Linq-To-Sql?	var query = db.TableAs.Where( a => a.TableBs.Count() > 0 )\n                      .Select( a => new { A = a, SumXY = a.X + a.Y } )\n                      .OrderBy( a => a.SumXY )\n                      .Take( 10 );	0
6313919	6248506	How to get all web services hosted in IIS using C#	IIS://hostname/W3SVC/1/root	0
8705326	8705074	C# Regular Expression to Find Words Containing One or More Matches	(?<TM>\w*(\?\?\w*)+)	0
18545558	18545536	ByteArray in c++	String^ postData = "username=" + UsernameInput->Text + "&password=" + PasswordInput->Text;\narray<Byte>^byteArray = Encoding::UTF8->GetBytes(postData);	0
15254803	15254612	How retry try statement in try/catch inside a foreach	IEnumerator<String> iter = list.GetEnumerator();\nbool bHasMore = iter.MoveNext();\nwhile (bHasMore) {\n  try {\n    ...\n    bHasMore = Iter.MoveNext();\n  }\n  catch ...\n}	0
20506647	20506592	SubString Text Selection	var str = "get directions from Sydney to Melbourne";\n\nvar parts = str.Split(new string[] { "from", "to" }, StringSplitOptions.None); // split it up\nvar from = parts[1]; // index 1 is from\nvar to = parts[2];   // index 2 is to\n\nConsole.WriteLine(from); // "Sydney"\nConsole.WriteLine(to);   // "Melbourne"	0
1848528	1848299	How to get the key of a Hashtable entry	foreach (DictionaryEntry de in infopathFields)\n        {        \n            string fieldName = de.Key as string;         \n                if (workflowProperties.Item.Fields.ContainsField(fieldName))        \n                {           \n                    workflowProperties.Item[fieldName] = infopathFields[fieldName];        \n                }    \n        }    \n\n        workflowProperties.Item.Update();	0
15769720	15769570	How to work with many connection in c# and ASP.NET?	using(SqlConnection conn = new SqlConnection(stringconection))\n{\n    conn.Open();\n    SqlCommand comando = new SqlCommand(/*my query update/delete/insert/select o execute sp*/,conn);\n    comando.Parameters.Add("@parameter1","value1");\n    comando.Parameters.Add("@parameter2","value2");\n    comando.Parameters.Add("@parameterN","valueN");\n    comando.ExecuteNonQuery();\n}	0
8788950	8788914	Retrive MAC Address with IP Address by using LINQ	NetworkInterface networkInterface = NetworkInterface.GetAllNetworkInterfaces().Where(ipProp => ipProp.GetIPProperties().UnicastAddresses.FirstOrDefault(ip => ip.Address.ToString().Equals("YOUR_IP")) != null).FirstOrDefault();\nif (networkInterface != null)\n{\n    Console.WriteLine(networkInterface.GetPhysicalAddress());\n}	0
6588594	6588516	Storing methods in a dictionary for custom Tcp or Udp server. Is it a good idea? C#	public abstract class MyAbstractNetCommand {   \n\n     public abstract void ExecuteCommand();\n} \n\npublic class ConcreteCommand : MyAbstractNetCommand {\n\n    /*Here additional ConcreteCommand specific methods and state members*/\n\n    public override ExecuteCommand() {\n       // concrete iplementation\n    }\n}	0
18242484	17876059	Implement Receipt verification for Apple Store Receipt in C#	public class receipt\n{\n    public string original_purchase_date_pst { get; set; }\n    public string original_transaction_id { get; set; }\n    public string original_purchase_date_ms { get; set; }\n    public string transaction_id { get; set; }\n    public string quantity { get; set; }\n    public string product_id { get; set; }\n    public string bvrs { get; set; }\n    public string purchase_date_ms { get; set; }\n    public string purchase_date { get; set; }\n    public string original_purchase_date { get; set; }\n    public string purchase_date_pst { get; set; }\n    public string bid { get; set; }\n    public string item_id { get; set; }\n}	0
28109888	28109297	c# Serial comms Read data and add to an array	var readQueue = string.Empty;\n\nprivate void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)\n{\n    readQueue += port.ReadExisting();\n\n    while (readQueue.Substring(1).Contains(@"\"))\n    {\n        var slashPos = readQueue.IndexOf(@"\",1);\n\n        var completeEntry = readQueue.Substring(0, slashPos);\n\n        Console.WriteLine(completeEntry);\n\n        readQueue = readQueue.Substring(slashPos);\n    }\n\n}	0
4578569	4578268	How to: Avoid Inserting Related Entities?	public void SaveOrder(Order order)     \n{         \n  using (var repository = new StoreEntities())         \n  {             \n    // Add order - calling add object marks Order and all entities in its \n    // object graph as Added - they will be inserted to database             \n    repository.Orders.AddObject(order);              \n\n    // You don't need to add order items because they should be added together \n    // with order\n\n    // But you don't want to insert Products again, do you?\n    // So you have to say that Products are not Added but Unchanged             \n    foreach (var orderItem in order.OrderItems)             \n    {                 \n      // Not sure how to do it with your repository but with ObjectContext \n      // you can do\n      // context.ObjectStateManager.ChangeObjectState(orderItem.Product, \n      //   EntityState.Unchanged);  \n    }     \n  }\n}	0
15618863	15618585	can't figure out how to do multiple joins in linq to EF	var result = \nfrom stu in SyStudent\njoin schsta in syschoolstatus on stu.syschoolstatusid equals schsta.syschoolstatusid //inner\njoin systa in SyStatus on schsta.SyStatusId equals systa.SyStatusId //innner\nfrom pic in cmstudentpicture.Where(x => x.systudentid = stu.systudentid).DefaultIfEmpty() //outer \nwhere stu.sycampusid = 6\nselect new{\n    stu,\n    schsta,\n    systa,\n    pic\n};	0
31873243	31872620	Regex Help String Matching	int i = 0;\n\n        string[] words = textBox1.Text.Split('#');\n\n        foreach (string word in words)\n        {\n            if (word.StartsWith("CAT_DOG_") && (!word.EndsWith(i.ToString())) )\n            {\n                //process here\n                MessageBox.Show("match is: " + word);\n            }\n        }	0
19855387	19855319	Convert SQL Query to IList<T> using of Dapper	public static IList<DomainClass> GetAllDomains()\n{\n    using (var con = new SqlConnection(Properties.Settings.Default.YourConnection))\n    {\n        const String sql = "Select sex, Id, Name  From ATest ORDER BY Name ASC;";\n        con.Open();\n        IList<DomainClass> domains = con.Query<DomainClass>(sql).ToList();\n        return domains;\n    }\n}	0
27622033	27621585	Parsing XML and extracting nodes	var xml = XElement.Load("test.xml");\n\n    foreach (var bookEl in xml.Elements("book"))\n    {\n        Console.WriteLine("Genre: " + bookEl.Attribute("genre").Value\n            + " " + "Publication: " + bookEl.Attribute("publicationdate").Value\n            + " " + "ISBN: " + bookEl.Attribute("ISBN").Value);\n        Console.WriteLine("Title: " + bookEl.Element("title").Value);\n        Console.WriteLine("Author: " + bookEl.Element("author").Element("first-name").Value \n            + " " + bookEl.Element("author").Element("last-name").Value);\n        Console.WriteLine("Price: " + bookEl.Element("price").Value);\n    }	0
5964462	5957774	Performing Inserts and Updates with Dapper	val = "my value";\ncnn.Execute("insert Table(val) values(@val)", new {val});\n\ncnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});	0
25823245	25822941	How to make Form1 call a method by command of Form2	Form2 userF = new Form2(this); // pass this to the constructor\nuserF.Show();	0
12346693	12346354	How do I hide & show form at a specific time in C#?	private void ProcessTimerEvent(object obj)\n{\n    if (this.InvokeRequired)\n    {\n        this.Invoke(new Action<object>(this.ProcessTimerEvent), obj);\n    }\n    else\n    {\n         this.Show();\n    }\n}	0
31301181	31300728	How to work on multiple windows in WPF	private async void BeginProcessingAsync(Data d)\n{\n    //Show to user that task is running\n    this.IsLoading = true; // Show a loading icon or something.\n\n    //Execute the long running task asynchronously\n    await Task.Run(() =>  LongRunningMethod(d));\n\n    //Anything after the await line will be executed only after the task is finished.\n    this.IsLoading = false;\n    DoSomethingWithFinishedData(d);\n}	0
19301246	19301137	Need to insert header row into csv when converting xml to CSV	String s=String.Join(",",doc.Descendants("fruit")\n                            .Elements()\n                            .Select(x=>x.Attribute("data").Value));	0
10349233	10349012	Correct approach on implementing abstract factory pattern?	var factory = DbProviderFactories.GetFactory("System.Data.OracleClient");\nDbConnection connection = factory.CreateConnection();	0
2089139	2089126	how to manually compile a C# project?	msbuild myApp.csproj	0
20503590	20503363	How to acces global variable in classes using the program	public class Dice\n{\n    public static int Roll()\n    {\n        // Your Code\n    }\n}	0
7474553	7474297	C# and Moq, raise event declared in interface from abstract class mock	var baseMock = new Mock<AbstractBase>();\nvar inpcMock = baseMock.As<INotifyPropertyChanged>();\n\n// ...setup event...\n\npropertyChangedMapper.Subscribe(inpcMock.Object);\n\n// ... assertions ...	0
15140951	15140911	Virtual method called from derived instead of base	public void Foo(Base b)\n{\n    b.VirtualMethod();\n}	0
3142193	3142001	How can I verify signature of a Powershell .ps1 script using C#?	using System.Collections.ObjectModel;\nusing System.Management.Automation;\nusing System.Management.Automation.Runspaces;\n\nprivate bool VerifyPowerShellScriptSignature()\n{\n    using (var runspaceInvoke = new RunspaceInvoke())\n    {\n        string path = "C:\\Windows\\system32\\WindowsPowerShell\\v1.0\\" +\n                      "Modules\\PSDiagnostics\\PSDiagnostics.psm1";\n        Collection<PSObject> results =\n            runspaceInvoke.Invoke("Get-AuthenticodeSignature " + path);\n        Signature signature = results[0].BaseObject as Signature;\n        return signature == null ? false : \n                                  (signature.Status == SignatureStatus.Valid);\n    }\n}	0
24243078	24243006	Want to remove time from date in dropdownlist?	ddlPaperDate.DataTextFormatString = "d";	0
27497819	27385981	Million inserts: SqlBulkCopy timeout	bc.BatchSize = 10000;\nbc.BulkCopyTimeout = 0;	0
4721657	4715876	How to run another app as administrator on Windows XP	ProcessStartInfo processStartInfo = new ProcessStartInfo("path", "args");\nprocessStartInfo.Verb = "runas";\n\nusing (Process process = new Process())\n{\n   process.StartInfo = processStartInfo;\n   process.Start();\n   process.WaitForExit();\n}	0
15104270	15104039	No intellisense for extension methods	(10).GetNegative()	0
4669011	4660817	Setting object properties from other object via reflection	//Copy the properties\n                foreach ( PropertyInfo oPropertyInfo in oCostDept.GetType().GetProperties() )\n                {\n                    //Check the method is not static\n                    if ( !oPropertyInfo.GetGetMethod().IsStatic )\n                    {\n                        //Check this property can write\n                        if ( this.GetType().GetProperty( oPropertyInfo.Name ).CanWrite )\n                        {\n                            //Check the supplied property can read\n                            if ( oPropertyInfo.CanRead )\n                            {\n                                //Update the properties on this object\n                                this.GetType().GetProperty( oPropertyInfo.Name ).SetValue( this, oPropertyInfo.GetValue( oCostDept, null ), null );\n                            }\n                        }\n                    }\n                }	0
5644247	5644238	Can I have defaults for parameters in C#?	public ActionResult Index(string caller_id, int id = 0)	0
16247952	16247838	Drop Down a Combobox on button click	private void button1_Click(object sender, EventArgs e)\n    {\n        comboBox1.DroppedDown = true;\n    }	0
16833294	16832951	set window title from listboxitem name	private void seznamSporocil_MouseDoubleClick(object sender, MouseButtonEventArgs e)\n    {\n        var listBox = sender as ListBox;\n        var item = listBox.SelectedItem as ListBoxItem;\n\n        var newWindow = new Window1();\n        newWindow.Title = item.Content.ToString();\n        newWindow.Show();\n    }	0
9254964	9254887	convert json to c# list of objects	class MovieCollection {\n        public IEnumerable<Movie> movies { get; set; }\n}\n\nclass Movie {\n        public string title { get; set; }\n}\n\nclass Program {\n        static void Main(string[] args)\n        {\n                string jsonString = @"{""movies"":[{""id"":""1"",""title"":""Sherlock""},{""id"":""2"",""title"":""The Matrix""}]}";\n                JavaScriptSerializer serializer = new JavaScriptSerializer();\n                MovieCollection collection = serializer.Deserialize<MovieCollection>(jsonString);\n        }\n}	0
2643032	2642932	Console Application to emulate command line	[DllImport("kernel32.dll")] \npublic static extern bool SetConsoleTextAttribute(\n                            IntPtr hConsoleOutput, int wAttributes);	0
33949696	33928426	how to debug delete button action in Lightswitch?	screen.Items.deleteSelected();	0
11186763	11185317	asp.net Download files from protected server	class WebClientWithCookies: WebClient\n{\n    private CookieContainer _container = new CookieContainer();\n\n    protected override WebRequest GetWebRequest(Uri address) \n    {\n        HttpWebRequest request = base.GetWebRequest(address) as HttpWebRequest; \n\n        if (request != null) \n        { \n            request.Method = "Post";\n            request.CookieContainer = _container; \n        } \n\n        return request;\n    }\n}	0
23014726	23002029	How to access NavigationController.PushViewController under UITableViewSource?	UITableViewController _parent;\n\npublic RootTableSource (IEnumerable<VendorDetails> items, UITableViewController parent)\n{\n    tableItems = items.ToList (); \n    _parent = parent;\n}\n\n\npublic override void RowSelected (UITableView tableView, NSIndexPath indexPath)\n{\n    tableView.DeselectRow (indexPath, true); \n\n    _parent.NavigationController.PushViewController(...);\n}	0
17831521	17695482	Setting the message of a custom Exception without passing it to the base constructor	public CustomException(dynamic json) : base(HumanReadable(json)) {}\nprivate static string HumanReadable(dynamic json) {\n    return whatever you need to;\n}	0
4695752	4695743	2 dimensional array in C#	List<T>	0
3967090	3966700	Regular expression to match characters in a string, excluding matches within HTML anchor elements	public static void Parse()\n{\n    string htmlFragment =\n        @"\n    I want to match  the word 'highlight' in a string. But I don't want to match\n    highlight when it is contained in an HTML anchor element. The expression\n    should not match highlight in the following text: <a href='#'>highlight</a> more\n    ";\n    HtmlDocument htmlDocument = new HtmlAgilityPack.HtmlDocument();\n    htmlDocument.LoadHtml(htmlFragment);\n    foreach (HtmlNode node in htmlDocument.DocumentNode.SelectNodes("//.").Where(FilterTextNodes()))\n    {\n        Console.WriteLine(node.OuterHtml);\n    }\n}\n\nprivate static Func<HtmlNode, bool> FilterTextNodes()\n{\n    return node => node.NodeType == HtmlNodeType.Text && node.ParentNode != null && node.ParentNode.Name != "a" && node.OuterHtml.Contains("highlight");\n}	0
4942291	4942208	assign text value to buttons from database in .net?	Form.Controls.Add()	0
5734953	5712008	Selenium2 + Yet another file upload	AutoItX3Lib.AutoItX3 au3 = new AutoItX3Lib.AutoItX3();\nau3.WinWait("Select file to upload");\nau3.WinActivate("Select file to upload");\nau3.Send("C:\\Documents and Settings\\user\\Desktop\\area51.png");\nau3.Send("{ENTER}");	0
16664533	16643936	XtraGrid shows blank row when binding it through DataTable	gridControl1.DataMember = "YourDataTableName";	0
34319275	34319043	How can I send a File over a REST API?	RestRequst.AddFile()	0
32517262	32504481	Aggregate Query Conversion From Mongo DB to C#	var aggregateArgs = new AggregateArgs();\n                aggregateArgs.Pipeline = new[]    \n                {\n                    new BsonDocument("$match", new BsonDocument("$and",\n                        new BsonArray().Add(new BsonDocument("Users.UserId", new BsonDocument("$all", \n                            new BsonArray().Add(paginationData.UserId).Add(paginationData.Id)))))),          \n                    new BsonDocument("$unwind", "$Posts"), \n                    new BsonDocument("$group", new BsonDocument\n                        {\n                            {"_id", "$_id"},                \n                            {"Posts", new BsonDocument("$push", "$Posts")},\n                        }),\n                    new BsonDocument("$sort", new BsonDocument("Posts.CreatedOn", -1)), \n                    new BsonDocument("$skip", paginationData.StartIndex - 1),\n                    new BsonDocument("$limit", paginationData.PageSize)\n                };	0
20520340	20520032	Trying to convert string to a value	public static object GetValue(string propertyName)\n{\n    var property = typeof(Names).GetField(propertyName);\n    return property.GetValue(null);\n}\n\nprivate static void Main(string[] args)\n{\n    string res = GetValue("One") as string;   // "Value of One"\n\n    Console.Read();\n}	0
293848	293582	How can I view the changes made after a revision is committed and parse it for comments?	static void Main(string[] args)\n{\n  SvnHookArguments ha;\n  if (!SvnHookArguments.ParseHookArguments(args, SvnHookType.PostCommit, false, out ha))\n  {\n    Console.Error.WriteLine("Invalid arguments");\n    Environment.Exit(1);\n  }\n\n  using (SvnLookClient cl = new SvnLookClient())\n  {\n    SvnChangeInfoEventArgs ci;\n    cl.GetChangeInfo(ha.LookOrigin, out ci);\n\n    // ci contains information on the commit e.g.\n    Console.WriteLine(ci.LogMessage); // Has log message\n\n    foreach(SvnChangeItem i in ci.ChangedPaths)\n    {\n       //\n    }\n  }\n}	0
8560306	8560265	C# Database Access: Best method to use for getting data	using (var context = new YourDatabaseEntities())\n{\n    var elements = (from c in context.YourTable where c.TaskId == taskId select c);\n}	0
13787034	13731509	How to have objects/Controls GC'd despite being subscribed to an event	event_name = null;	0
4991275	4989055	TaskDialog in WPF	YourApp.vshost.exe.manifest	0
2840462	2840438	Lambda returning another lambda	public delegate Lambda Lambda()	0
8033763	8033732	How to get a list of all cities in the world and their correponding time zone information including DST	System.TimeZoneInfo.GetSystemTimeZones()	0
8055272	8054235	 Selecting XML nodes?	var xml = XDocument.Load("input.xml");\nvar node = (from file in xml.Descendants("File")\n           where (string)file.Element("FileName") == "logfile1.log"\n           select file).Single();	0
9578107	9577349	Delete a row from a SQL Server table	public static void deleteRow(string table, string columnName, string IDNumber)\n    {\n    try\n    {\n    using (SqlConnection con = new SqlConnection(Global.connectionString))\n    {\n         con.Open();\n         using (SqlCommand command = new SqlCommand("DELETE FROM " + table + " WHERE " + columnName + " = '" + IDNumber+"'", con))\n         {\n               command.ExecuteNonQuery();\n         }\n         con.Close();\n    }\n    }\n    catch (SystemException ex)\n       {\n       MessageBox.Show(string.Format("An error occurred: {0}", ex.Message));\n       }\n    }\n }	0
20245336	20117847	Cordova Plugin Development: Prevent escaping of parameters passed in the plugin	cordova.exec(win, fain, "Plugin", "method", [JSON.stringify(data)]);	0
3709433	3709323	What is a good approach in MS SQL Server 2008 to join on a "best" match?	select\n    c.Id,\n    c.TelephoneNumber,\n    (select top 1 \n         Scale \n\n         from Rate r \n\n         where c.TelephoneNumber like r.Prefix + '%' order by Scale desc\n    ) as Scale\n\nfrom Call c	0
2850349	2850317	POST to a webpage from C# app	private void btnSubmit_Click(object sender, EventArgs e)\n{\n    var postData = Encoding.Default.GetBytes("Fullname=Test");\n    webBrowser1.Navigate(\n        "http://www.url.com/Default.aspx", \n        null, \n        postData, \n        "Content-Type: application/x-www-form-urlencoded" + Environment.NewLine\n    );\n}	0
6762170	6762077	EF4 Code First: Parent/Child relationship in same table, how to get inverse property?	public virtual Item Parent {get;set;}	0
28032905	28032705	Retrieve/Update EF Entity using string representation of column - code first	var e = db.Entry(new User() {Id =1, Name = "test"});\nvar property = e.CurrentValues.PropertyNames.FirstOrDefault(p => p == colName);\ne.CurrentValues[property] = colValue;	0
14538445	14527285	Unit Testing a Factory with a Generator	[Test]\npublic void RegionFactoryDelegatesToRegionGenerator()\n{\n    var mockGenerator = new Mock<IMapRegiongenerator>();\n    var factory = new MapRegionFactory(mockGenerator.Object);\n\n    var expectedRegion = new Region();\n    var regionSize = CreateRandomRegionSize();\n    mockGenerator.Setup(g=>g.GenerateRegion(regionSize)).Returns(expectedRegion);\n\n    factory.SetRegionSize(regionSize);\n    Assert.That(factory.GetRegion(), Is.SameAs(expectedRegion));\n}	0
27689360	27689077	Converting C application to c# char[]	public struct msg_next_match \n{\n    public int tatami;\n    public int category;\n    public int match;\n    public int minutes;\n    public int match_time;\n    public int gs_time;\n    public int rep_time;\n    public int rest_time;\n    public char pin_time_ippon;\n    public char pin_time_wazaari;\n    public char pin_time_yuko;\n    public char pin_time_koka;\n    public fixed char cat_1[32];\n    public fixed char blue_1[64];\n    public fixed char white_1[64];\n    public fixed char cat_2[32];\n    public fixed char blue_2[64];\n    public fixed char white_2[64];\n    public int  flags;\n};	0
32393099	32392996	How to listen to the state of a running process using C#	var process = Process.Start(...);\nprocess.WaitForExit();	0
862592	862570	How can I use the RelayCommand in wpf?	RelayCommand _saveCommand;\npublic ICommand SaveCommand\n{\n    get\n    {\n        if (_saveCommand == null)\n        {\n            _saveCommand = new RelayCommand(param => this.Save(),\n                param => this.CanSave );\n        }\n        return _saveCommand;\n    }\n}	0
33261332	33260773	automapper memberList parameter	Mapper.CreateMap(typeof(Customer), typeof(CustomerViewItem)).ForMember("Id", opt => opt.Ignore());	0
8693817	8684872	Make a client download a file from a path that is not publicly accessible?	String FileName = "File.zip";\n            String FilePath = "C:/Test/" + FileName; //Replace this\n            System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;\n            response.ClearContent();\n            response.Clear();\n            response.ContentType = "text/plain";\n            response.AddHeader("Content-Disposition", "attachment; filename=" + FileName + ";");\n            response.TransmitFile(FilePath);\n            response.Flush();\n            response.End();	0
17995578	17990590	Entity Framework T4 templates, how to find out if a relationship is a proper 1 to many	if (navProperty.FromEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many &&\n    navProperty.ToEndMember.RelationshipMultiplicity == RelationshipMultiplicity.Many)\n{\n    // deal with many to many link collections here...\n}	0
27891696	27891651	How to only allow the current month in Month Calender	DateTime?today?=?DateTime.Today;\nDateTime?firstDayInMonth?=?new?DateTime(today.Year,?today.Month,?1);\nDateTime?lastDayInMonth?=?new?DateTime(today.Year,?today.Month,?DateTime.DaysInMonth(today.Year,?today.Month));	0
848201	847538	Nested generic collections: How to implement reference from item to container?	abstract class OuterBase<TInnerItem>\n{\n}\n\nclass Outer<TInner, TInnerItem> : OuterBase<TInnerItem> where TInner : Inner<TInnerItem>\n{\n    public void Add(TInner item)\n    {\n        item.Outer = this; // Compiles\n    }\n}\n\nclass Inner<TInnerItem> : ICollection<TInnerItem>\n{\n    OuterBase<TInnerItem> _outer;\n\n    public OuterBase<TInnerItem> Outer\n    {\n        set { _outer = value; }\n    }\n}	0
22313870	22313657	Add items to comboBox	.DataSource	0
13988526	13988014	.NET Regex to detect and split the strings	string source = "#if [Customer.OrderQuantity] > 5 #then 1000 #if [Customer.OrderQuantity] < 5 #then 500 #else 100";\n\nstring[] result = Regex.Split(source, @"\s*(?=#(?:if|else))");\n\nforeach (string a in result) {\n    Console.WriteLine(a);\n}	0
2653988	2653969	How do I determine if the executing assembly is a web app or winform/console?	if (!String.IsNullOrEmpty(HttpRuntime.AppDomainAppVirtualPath))\n    //ASP.Net\nelse \n    //Non-ASP.Net	0
34460251	34460025	Permission To Access Pages	string session_string="";\nSqlConnection cn = new SqlConnection(YOUR_CONNECTION_STRING);\ncn.open();\nSqlCommand cmd = new SqlCommand();\ncmd.Connection=cn;\ncmd.CommandType=CommandType.Text;\ncmd.CommandText="select name_of_pages from permission where username='YOUR_USERNAME'";\nSqlDataReader rdr = cmd.ExecuteReader();\nif(rdr.hasRows==true){\n    while(rdr.Read()){\n        session_string=rdr["name_of_pages"] + ",";//You need to declare this variable globally before\n        session_string=session_string + rdr["name_of_pages"] + ","; //USE THIS LINE , NOT PREVIOUS ONE\n    }\n}\nrdr.close();//DONT FORGET THIS ALSO\ncn.close();//DONT FORGET THIS\n    Session["pages"]=session_string;\n    //Now to check\n    if(Session["pages"].Contains("Index.aspx")){\n        //PERFORM SOMETHING POSITIVE\n\n    }\n    else\n    {\n        //PERFORM SOMETHING NEGATIVE\n    }	0
17568199	17568139	Want to split a string into 2 parts and holding each one in a different variable using c#	String data = "12:00pm";\nString time = data.substring(0, 5);\nString ampm = data.substring(5, 2);	0
16548436	16535589	How to access the MS Outlook mail using the EntryIDCollection?	Namespace.GetItemFromID	0
23851188	23850836	User Control, can we add event in the property panel?	public event EventHandler MyNewEvent;	0
4632152	4632103	StackOverFlowException - but oviously NO recursion/endless loop	Image.FromStream	0
5772258	5772219	How to use UPDATE in ado net	string sql2 = "UPDATE student SET moneyspent = moneyspent + @spent WHERE id=@id";\nSqlCommand myCommand2 = new SqlCommand(sql2, conn);\nmyCommand2.Parameters.AddWithValue("@spent", 50 )\nmyCommand2.Parameters.AddWithValue("@id", 1 )	0
1031871	1025670	How do you automatically resize columns in a DataGridView control AND allow the user to resize the columns on that same grid?	grd.DataSource = DT\n\n    'set autosize mode\n    grd.Columns(0).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells\n    grd.Columns(1).AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells\n    grd.Columns(2).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill\n\n    'datagrid has calculated it's widths so we can store them\n    For i = 0 To grd.Columns.Count - 1\n        'store autosized widths\n        Dim colw As Integer = grd.Columns(i).Width\n        'remove autosizing\n        grd.Columns(i).AutoSizeMode = DataGridViewAutoSizeColumnMode.None\n        'set width to calculated by autosize\n        grd.Columns(i).Width = colw\n    Next	0
9010870	9010806	Check if a file is in use, wait for it to finish	Process p = new Process();\np.StartInfo = startInfo;\np.WaitForExit();	0
31254524	31249393	How to grow an image gradually (from nothing) in WPF	DoubleAnimation anim = new DoubleAnimation(0, 1, (Duration)TimeSpan.FromSeconds(1.2));\nScaleTransform st = new ScaleTransform();\nst.ScaleX = 0;\nst.ScaleY = 0;      \nIMAGE.RenderTransform = st;\nst.BeginAnimation(ScaleTransform.ScaleXProperty, anim);\nst.BeginAnimation(ScaleTransform.ScaleYProperty, anim);	0
14903734	14883384	Displaying a picture stored in Storage file in a metroapp	private async void  Button_Click_1(object sender, RoutedEventArgs e)\n    {\n        // load file from document library. Note: select document library in capabilities and declare .png file type\n        string filename = "Logo.png";\n        Windows.Storage.StorageFile sampleFile = await Windows.Storage.KnownFolders.DocumentsLibrary.GetFileAsync(filename);\n        // load file from a local folder\n        //Windows.Storage.StorageFile sampleFile = sampleFile = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync("Assets\\Logo.png");\n\n        BitmapImage img = new BitmapImage();\n        img = await LoadImage(sampleFile);\n        myImage.Source = img;\n    }\n\n    private static async Task<BitmapImage> LoadImage(StorageFile file)\n    {\n        BitmapImage bitmapImage = new BitmapImage();\n        FileRandomAccessStream stream = (FileRandomAccessStream)await file.OpenAsync(FileAccessMode.Read);\n\n        bitmapImage.SetSource(stream);\n\n        return bitmapImage;\n\n    }	0
13407690	13407669	How to use array member?	schema.name = "schemaName";\nschema.tables = new Tables[10];\nschema.tables[0].name = "tables1";	0
33457302	33454529	Convert Latin characters from Shift JIS to Latin characters in Unicode	NormalizeString()	0
17186453	17186035	bind many dropdownlist in a continous fashion	for (int i = 1; i <= 10; i++)\n        {\n            DropDownList drp = (DropDownList)panel1.FindControl("ddlxx" + i.ToString());//panel1 is your panel which contain dropdown ddlxx1,ddlxx2,ddlxx3...\n            drp.DataSource = Prod.GetComponents();\n            drp.DataTextField = "ComponentID";\n            drp.DataValueField = "ComponentName";\n            drp.DataBind();\n        }	0
33932808	33907026	Code that Builds in Visual Studio Won't Build in TFS	/p:VisualStudioVersion=14.0	0
26025116	26025092	Decreasing velocity of my space ship	velocity /= 2f;	0
12449836	12449803	How to disable a contextmenu for a panel	panel1.ContextMenu = null;	0
33787848	33787784	Limit counter of products	plus.Click += delegate\n    {\n        counttext.Text = string.Format("{0}", ++count);\n    };  \n    minus.Click += delegate\n    {\n        counttext.Text = string.Format("{0}", count > 0 ? --count : 0);\n    };	0
18988279	18988201	Tokenize a string in C# which delimeters contains some parts of other delimeters	//Put operators in order of 'complexity'. Since >= contains > and =, comes before them\nstring[] operators = new string[] {">=", "!=", ">", "="};\nstring expression = "(3>=4)!=(3>4)";\n\nforeach (string operator in operators)\n{\n    //Perform logic of creating expression tree here\n}	0
9749227	9749141	C# How can I paste formatted text from clipboard to the RichTextBox	richTextBox1.Text = Clipboard.GetText(TextDataFormat.Rtf);	0
26647976	26645947	Sqlite with windows phone 8 app development	protected override void OnNavigatedTo(NavigationEventArgs e)\n    {\n                AddInfo();\n                ReadHistoryList_Loaded();\n    }	0
4939689	4939660	Parsing XML in C# from stream	XDocument doc = XDocument.Load(@"test.xml");\nXNamespace serv = "http://www.webex.com/schemas/2002/06/service";\nvar result = doc.Descendants(serv + "result").First().Value;	0
7298652	7298611	How to show full file path in TextBox?	TextBox1.Text = string.Format("{0}/{1}",\n    Path.GetDirectoryName(fileData),openFileDialog1.FileName);	0
25718353	25711786	How to determine the parent of child menu item in ToolStripMenu?	private void mnuDatabase1_Click(object sender, ...)\n{\n    ToolStripMenuItem MyMenuItem = (ToolStripMenuItem)sender;\n    ToolStripMenuItem parent = (ToolStripMenuItem)MyMenuItem.OwnerItem;\n    if (parent.Name == "mnuAdd")\n        //Add Menu\n    else if (parent.Name == "mnuEdit")\n        //Edit Menu\n    if (parent.Name == "mnuDelete")\n        //Delete Menu\n}	0
222640	222598	How do I clone a generic list in C#?	static class Extensions\n{\n    public static IList<T> Clone<T>(this IList<T> listToClone) where T: ICloneable\n    {\n        return listToClone.Select(item => (T)item.Clone()).ToList();\n    }\n}	0
2018343	2018281	Winform DatagridView Numeric Column Sorting	private void dataGridView1_SortCompare(object sender, DataGridViewSortCompareEventArgs e)\n{\n    if (e.Column.Index == 0)\n    {\n        if (double.Parse(e.CellValue1.ToString()) > double.Parse(e.CellValue2.ToString()))\n        {\n            e.SortResult = 1;\n        }\n        else if (double.Parse(e.CellValue1.ToString()) < double.Parse(e.CellValue2.ToString()))\n        {\n            e.SortResult = -1;\n        }             \n        else\n        {\n            e.SortResult = 0;\n        }\n        e.Handled = true;\n   }\n}	0
8829287	8826743	How to capture javascript HTTP redirection in c#?	window.location = "/home";	0
31652289	31652171	Can't convert from String to Char	DateTime dt = Convert.ToDateTime(reader["date"]);\nint year = dt.Year;\nint month = dt.Month;\nint day = dt.Day;	0
22627555	22627427	How to terminate session in windows phone 8?	while (this.NavigationService.BackStack.Any())\n {\n          this.NavigationService.RemoveBackEntry();\n }	0
4215678	4215595	C# Removing separator characters from quoted strings	string pattern = "\"([^\"]+)\"";\nvalue = Regex.Match(textToSearch, pattern).Value;\n\nstring[] removalCharacters = {",",";"}; //or any other characters\nforeach (string character in removalCharacters)\n{\n    value = value.Replace(character, "");\n}	0
23043534	23042605	How do I update a ViewModel in a view with AJAX?	public JsonResult ActionName(){\nJsonObjectWhatEver value = new JsonObjectWhatEver();\nreturn Json(value,JsonBehaviour.AllowGet);   /// check the name is it JsonBehaviour or some thing simillar\n}	0
19110420	19110143	Conversion of Unicode to characters in JavaScript confirm window	Button1.Attributes.Add("OnClick", "clicked('" +\n     HttpUtility.HtmlDecode("R&#233;cup&#233;ration de frigorig&#232;ne" + "')");	0
31054025	31053761	Clickable Grid in C# Winform	dataGridView1.CellClick += new DataGridViewCellEventHandler(dataGridView1_CellClick);\n\n    void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)\n    {\n        dataGridView1[e.ColumnIndex, e.RowIndex].Style.BackColor = Color.White;\n    }	0
10276324	10276228	Timespan to dateTime conversion	DateTime dt = new DateTime(2012, 01, 01);\n TimeSpan ts = new TimeSpan(1, 0, 0, 0, 0);\n dt = dt + ts;	0
12796509	12795667	How to reset Thread.CurrentPrincipal to unauthenticated in a Unit Test	Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(""), new string[0]);	0
277790	277783	How to correctly open a FileStream for usage with an XDocument	XDocument doc;\n\nusing (StreamReader reader = File.OpenText(filename))\n{\n  doc = XDocument.Load(reader);\n  doc.Root.Add(entry);\n}\n\ndoc.Save(filename);	0
29882419	29882338	Set Method isn't protected, how do I make it protected?	public class Person\n{\n    public string Name { get; protected set; }   \n}	0
32677658	32677600	change localization in C# on Windows Universal 8.1	ApplicationLanguages.PrimaryLanguageOverride	0
20909980	20909897	How to get text from long list selector item in Windows Phone 8?	ShoppingList sitem = LLS.SelectedItem as ShoppingList;\nstring item = string.empty;\nif ( sitem != null )\n{\n item = sitem. (property where you text is stored)\n}	0
1088244	1088212	How do I perform Date Comparison in EF query?	var query = from e in db.MyTable\n            where e.AsOfDate <= DateTime.Now.Date\n            select e;	0
24061684	24061615	How to detect if a MySql query was successful or not and output a message?	try\n        {\n            connection.Open();\n            cmd = connection.CreateCommand();\n            cmd.CommandText = "INSERT INTO BOOK(ISBN, title, author, publisher,imgPath, catalogID) VALUES ('" + isbn + "','" + title + "','" + author + "','" + publisher + "','" + localPath + "','" + catalogid + "')";\n            int a= cmd.ExecuteNonQuery();\n             if(a>0)\n               //updated.\n             else\n              //Not updated.\n        }\ncatch (Exception)\n        {\n           //Not updated.\n        }	0
10870606	10870533	How to output windows Alt keycodes in a C# console app	Console.WriteLine("??");	0
18660130	18660069	There is Already an open DataReader that must be closed first	public ActionResult Index()\n{\n    var products = _db.Products.ToArray() // force loading the results from database \n                                           // and close the datareader\n\n    var viewModel = products.Select(product => GetMedicalProductViewModel(product));\n\n    return View(viewModel);\n}	0
14663499	14663385	String saves numbers wrong	string year = idNumber.Substring(0, 2);\nstring month = idNumber.Substring(2, 2);\nstring day = idNumber.Substring(4, 2);	0
6089823	6089670	Insert into all columns of int same value	foreach(PropertyInfo prop in o.GetType().GetProperties()) \n{\n    if(prop.PropertyType == typeof(int))\n        prop.SetValue(o, newValue, null);\n}	0
7676703	7676623	ToolTip for asp.net page. Have to display 3 tables as tooltip	Menu mainmenu = new Menu();\n        MenuItem NavigationMenu = new MenuItem();\n        NavigationMenu.Text = "This is a text";\n        NavigationMenu.NavigateUrl = "../somepage.aspx";\n        mainmenu.Items.Add(NavigationMenu);	0
27058287	27057839	How to hide particular listitems that are used for making a menu for particular users?	// Get employee from Session\nEmployee employee = (Employee)Session["Employee"];\n\n// Check if employee exists\nif(employee != null)\n{\n    RenderMenu(employee);\n}\n\n// Method to render list\nprivate void RenderMenu(Employee employee)\n{\n    StringBuilder _menu = new StringBuilder();\n    _menu.Append("<ul>");\n\n    // Property boolean that indicates if the employee is an admin\n    if(employee.IsAdmin)\n    {\n        //Add items for admin\n    } \n\n    _menu.Append("</ul>");\n\n    // Panel on the aspx page where you add the menu control\n    this.pnlMenu.Controls.Add(new LiteralControl() { Text = _menu.ToString() });\n}	0
34351043	34336283	How to periodically update content in Win 8.1 app	the timer can't handle the async part	0
25852509	25852385	Exception Handiling in Independent functions, without stoping the C# Console Application	static private void WithCatch(Action f)\n{\n    try\n    {\n        f();\n    }\n    catch (System.TimeoutException ex)\n    {\n        Console.WriteLine("System.TimeoutException");\n    }\n    catch (System.Exception ex)\n    {\n        Console.WriteLine("System.Exception");\n    }\n}\nstatic public void Main(string[] args)\n{\n    WithCatch(() => {\n        for (int i = 0; i < 10; i++)\n           ONE_IndependentProcess(i);\n    });\n    // You could also do this inside the for loop for each one if you want\n    // to attempt all 10 even if one fails:\n    //for (int i = 0; i < 10; i++)\n    //    WithCatch(() => {ONE_IndependentProcess(i);});\n\n    WithCatch(() => {TWO_IndependentProcess();});\n    WithCatch(() => {THR_IndependentProcess();});\n}	0
33911730	33911464	Removing the helping words from sentence	private static HashSet<String> s_StopWords = \n  new HashSet<String>(StringComparer.OrdinalIgnoreCase) {\n    "is", "am", "are", "were", "was", "do", "does", "to", "from", // etc.\n};\n\nprivate static Char[] s_Separators = new Char[] {\n  '\r', '\n', ' ', '\t', '.', ',', '!', '?', '"', //TODO: check this list \n};\n\n...\n\nString source = "I go to school";\n\n// ["I", "go", "school"] - "to" being a stop word is removed\nString[] words = source\n  .Split(s_Separators, StringSplitOptions.RemoveEmptyEntries)\n  .Where(word => !s_StopWords.Contains(word))\n  .ToArray();\n\n// Combine back: "I go school"\nString result = String.Join(" ", words);	0
11401770	11400445	Capture client area of another program in C#?	Process[] process = Process.GetProcesses();\nforeach (var p in process)\n{\n    selectedProgram = listView1.SelectedItems.ToString();\n}	0
16194819	16194713	Writing to xml file but not with all results	stream.WriteLine("<name>" + txtName.Text + "</name>");\nstream.WriteLine("<email>" + txtName.Text + "</email>");\nstream.WriteLine("<age>" + txtName.Text + "</age>");	0
371508	371418	Can you represent CSV data in Google's Protocol Buffer format?	message CsvFile {\n    repeated CsvHeader header = 1;\n    repeated CsvRow row = 2;\n}\n\nmessage CsvHeader {\n    require string name = 1;\n    require ColumnType type = 2;\n}\n\nenum ColumnType {\n    DECIMAL = 1;\n    STRING = 2;\n}\n\nmessage CsvRow {\n    repeated CsvValue value = 1;\n}\n\n// Note that the column is implicit based on position within row    \nmessage CsvValue {\n    optional string string_value = 1;\n    optional Decimal decimal_value = 2;\n}\n\nmessage Decimal {\n    // However you want to represent it (there are various options here)\n}	0
7685619	7685589	cast from List<EntityObject> to EntityObject	public void CreateNewAuthor(List<Author> newAuthors)\n{\n    foreach (Author newAuthor in newAuthors)\n    {\n        publishContext.AddToAuthors(newAuthor);\n    }\n}	0
21245238	21174002	How do I write an index to get the total number of objects in a collection across documents in RavenDB?	public class Contacts_GetCount: AbstractIndexCreationTask<ClientContactsModel, Contacts_GetCount.ContactResult>\n{\n    public class ContactResult\n    {\n        public Guid ClientId { get; set; }\n        public int Total { get; set; }\n    }\n\n    public Contacts_GetCount()\n    {\n        Map = contacts => from contact in contacts\n            select new {\n                ClientId = contact.ClientId,\n                Total = contact.Contacts.Count\n            };\n\n        Reduce = results => from result in results\n            group result by result.ClientId\n            into g\n            select new {\n                ClientId = g.Key,\n                Total = g.Sum(x=>x.Total)\n            };\n    }\n}	0
13488043	13488006	Dynamically add a new text box when clicking a button	TextBox tb;\nstatic int i = 0;\nprotected void addnewtext_Click(object sender, EventArgs e)\n{\n        i++;\n    for(j=0;j<=i;j++)\n    {\n    tb = new TextBox();\n    tb.ID = j.ToString();\n\n    PlaceHolder1.Controls.Add(tb);\n    }\n\n}	0
22027999	22027817	How to convert a registry key to an Image	// get the registry-key\nRegistryKey wp = Registry.CurrentUser.OpenSubKey("Control Panel\\Desktop", false);\n\n// get the wallpaper filename\nstring sFileName = (string)wp.GetValue("Wallpaper");\n\n// finally load the image into picture box\npictureBox1.Image = Image.FromFile(sFileName);	0
25587597	25586637	uploading files from azure mobile windows phone 8.1	Put Blob	0
181863	181853	Mocking an attribute change on a parameter - using Moq	accountRepository\n    .Expect(r => r.InsertAccount(account))\n    .Callback(() => account.ID = 1);	0
11690152	11687062	get Office value off mysites in sharepoint 2010	var Office = profile[PropertyConstants.Office] != null ? profile[PropertyConstants.Office].Value : String.Empty;	0
1580232	1580199	Linq to Sql - Populate JOIN result into a List	DataLoadOptions dlo = new DataLoadOptions();\ndlo.LoadWith<Department>(d => d.Employees);\nusing (var dba = new MyDataContext())\n{\n  dba.LoadOptions = dlo;\n  var result = from d in dba.Department\n      select d;\n}	0
20431138	20431029	Open message box if row cells in a particular column are clicked	private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)	0
5964346	5964123	Run commandline from c# with parameters?	string command = @"C:\My Dir\MyFile.exe";\nstring args = "MyParam1 MyParam2";\n\nProcess process = new Process(); \nprocess.StartInfo.FileName = command; \nprocess.StartInfo.Arguments = args;\nprocess.Start();	0
21716227	21715618	How to get all controls in Content Page with C#?	List<Control> lst_controls = new List<Control>();\n        public void btnClick()\n        {\n             RetrieveAllControls(this.Page);\n             foreach(Control contrl in lst_controls)\n             {\n                     // all controls \n             }\n        }\n        public static void RetrieveAllControls(Control control)\n        {\n            foreach (Control ctr in control.Controls)\n            {\n                if (ctr != null)\n                {\n\n                    lst_controls.add(ctr);             \n                    if (ctr.HasControls())\n                    {\n                        RetrieveAllControls(ctr, strID);\n\n                    }\n                }\n            }\n            return null;\n        }	0
6943775	6943680	Populate a UserControl Gridview with a List of Objects	/// <summary>\n/// The test class for our example.\n/// </summary>\nclass TestObject\n{\n    public string Code { get; set; }\n    public string Text { get; set; }\n}\n\nvoid PopulateGrid()\n{\n    TestObject test1 = new TestObject()\n    {\n    Code = "code 1",\n    Text = "text 1"\n    };\n    TestObject test2 = new TestObject()\n    {\n    Code = "code 2",\n    Text = "text 2"\n    };\n    List<TestObject> list = new List<TestObject>();\n    list.Add(test1);\n    list.Add(test2);\n\n    dataGridView1.DataSource = list;\n}	0
3217654	3217651	How do I use random numbers in C#?	Random r = new Random();\nint nextValue = r.Next(0, 100); // Returns a random number from 0-99	0
4280461	4280434	Easiest way to display array of values in table in windows form C#	BindingList<T>	0
31484767	31484646	How to initialize a new multidimensional object array with a lower bound of 1?	(object[,])Array.CreateInstance(typeof(object), new int[] { 1, 1 }, new int[] { 1, 1 });	0
2389401	2389328	How to write generic IEnumerable<SelectListItem> extension method	public static IEnumerable<SelectListItem> ToSelectListItems(\n     this IEnumerable<T> items, \n     Func<T,string> nameSelector, \n     Func<T,string> valueSelector, \n     Func<T,bool> selected)\n{\n     return items.OrderBy(item => nameSelector(item))\n            .Select(item =>\n                    new SelectListItem\n                    {\n                        Selected = selected(item),\n                        Text = nameSelector(item),\n                        Value = valueSelector(item)\n                    });\n}	0
29199196	29199132	Unit testing a multi step flow in C#	[TestInitialize]	0
16578590	16578247	Need help on a simple string sort method from a string array	static void Main()\n    {\n        var strList1 = new[] { "TDC1ABF", "TDC1ABI", "TDC1ABO" };\n        var strList2 = new[] { "TDC2ABF", "TDC2ABI", "TDC2ABO" };\n        var strList3 = new[] { "TDC3ABF", "TDC3ABO", "TDC3ABI" };\n\n        var allItems = strList1.Concat(strList2).Concat(strList3);\n\n        var abfItems = allItems.Where(item => item.ToUpper().EndsWith("ABF"))\n            .OrderBy(item => item);\n        var abiItems = allItems.Where(item => item.ToUpper().EndsWith("ABI"))\n            .OrderBy(item => item);\n        var aboItems = allItems.Where(item => item.ToUpper().EndsWith("ABO"))\n            .OrderBy(item => item);\n    }	0
6042636	6042481	Use of anonymous method	names.ForEach(x=> Console.WriteLine(x));	0
17969552	17969411	Disable controls when a specific combo-box item is selected	private void cbalpha_SelectedIndexChanged(object sender, EventArgs e)\n    {\n\n        bool isEnabled = string.Compare(StringtDataChoiceorSelect.SelectedItem.ToString(),"(Initiate)",StringComparison.OrdinalIgnoreCase) == 0;\n        foreach (Control cb in this.Controls)\n            cb.Enabled = !isEnabled ;\n\n    }	0
11583216	11581816	Remove permStart and permEnd tags from document docx	foreach (PermStart p1 in wordD.MainDocumentPart.Document.Body.Descendants<PermStart>())\n                {\n                    p1.Parent.RemoveChild<PermStart>(p1);\n                }\n\n                foreach (PermEnd p2 in wordD.MainDocumentPart.Document.Body.Descendants<PermEnd>())\n                {\n                    p2.Parent.RemoveChild<PermEnd>(p2);\n                }\n                wordD.MainDocumentPart.Document.Save();	0
10978473	10978344	Executing a long-running method right before a page redirect in ASP.NET	Task.Factory.StartNew(() => Data.Common.Documents.Regenerate());	0
7992320	7992230	How to check out a document from a remote sharepoint server programatically (c#)	Web_Reference_Folder.Lists listService = new Web_Reference_Folder.Lists();\nlistService.Credentials = System.Net.CredentialCache.DefaultCredentials;\nstring fileCheckout = "http://Server_Name/sites/Subsite/Shared Documents/MyFile.txt";\nbool myResults = listService.CheckOutFile(fileCheckout, "true", "20 Jun 2006 12:00:00 GMT");	0
17521755	17519232	How to change ASP MVC3 completed method for async controller?	private JsonResult CompletedLogic(object param)\n{ ... }\n\npublic JsonResult FooCompleted(object result)\n{return CompletedLogic(result);}\n\npublic JsonResult BooCompleted(object result)\n{return CompletedLogic(result);}	0
2761197	2761163	ASP webservice serialization of properties	public int Sum \n{\n    get\n    {\n        return A+B;\n    }\n    set\n    {\n        throw new NotImplementedException("Can't serialize this direction.");\n    }\n}	0
16148266	16148195	How to get shortest representation of an enum flags value?	O(logn)	0
15589715	15450239	Access a specific row in DataReader	if (dReader.HasRows) {\n    while (dReader.Read()) {\n\n        if ( dReader["gameweekID"].ToString() == currentWeekId ) \n        {    \n            gameweekList.Text += "<div class=\"somethingSpecial\"><h4>Gameweek " + \n            (dReader["gameweekID"].ToString()) + "</h4></div>";\n        } \n        else \n        {\n            gameweekList.Text += "<div class=\"item\"><h4>Gameweek " + \n            (dReader["gameweekID"].ToString()) + "</h4></div>";\n        }\n    }\n} else {\n    gameweekList.Text = "Error Finding Gameweeks";\n}\ndReader.Close();\nconn.Close();	0
16304964	16304617	Best practice for storing and accessing common string literals	namespace EnumTest\n{\n    public enum enumRole : byte { projMgr = 2, docAdmin = 3, dataAdmin = 4, sysAdmin = 9, userAdmin = 5 };\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            enumRole myrole = enumRole.docAdmin;\n            if (myrole == enumRole.docAdmin) Console.WriteLine("I am docAdmin");\n            // i use the key to save to SQL and restore  \n            // in SQL have a fk table to match the enum\n            Console.WriteLine((byte)myrole);\n            myrole = (enumRole)9;\n            Console.WriteLine(myrole.ToString() + " " + ((byte)myrole).ToString());\n            Console.ReadLine();\n        }\n    }\n}	0
24145822	24142909	Remove color gradient from scaled unit bitmap	private Bitmap getBlankBitmap(int width, int height) {\n  Bitmap b = new Bitmap(width, height);\n  using (Graphics g = Graphics.FromImage(b)) {\n    g.Clear(Color.Red);\n  }\n  return b;\n}	0
20773043	20772933	Scroll in NumericUpDown	public Form1()\n    {\n        InitializeComponent();\n        numericUpDown1.MouseWheel += new System.Windows.Forms.MouseEventHandler(this.numericUpDown1_MouseWheel);\n    }\n\n    private void numericUpDown1_MouseWheel(object sender, System.Windows.Forms.MouseEventArgs e)\n    {\n        MessageBox.Show("hello");\n    }	0
8698054	8697965	Unexpected Response from my server while accessing it from a Client application in Silverlight	WebRequest.RegisterPrefix	0
21669039	21669001	Add an item to an ICollection inside of a Linq query	IEnumerable<User> users =\n    model\n        .Select(u => new User\n        {\n                Username = u.Username,\n                EmailAddress = u.EmailAddress,\n                Federations =\n                    u.FederatedUsername == null\n                    ? new List<Federation>() :\n                    (new []\n                        {\n                            new Federation()\n                            {\n                                FederatedUsername = u.FederatedUsername\n                            },\n                        }).ToList(),\n        });	0
5599220	5599111	Open a resource file with StreamReader?	string fileContent = Resource.text;\nusing (var reader = new StringReader(fileContent))\n{\n    string line;\n    while ((line = reader.ReadLine()) != null)\n    {\n        string[] split = line.Split('|');\n        string name = split[0];\n        string lastname = split[1];\n    }\n}	0
567872	567867	Closing an IE 'popup' window with script	ClientScript.RegisterClientScriptBlock(GetType(), "save", Utils.MakeScriptBlock("self.close();"));	0
27038634	27038399	Get SQL statement from a predicate?	DataContext.GetCommand Method	0
5540946	5540767	Apply DateTime offset to US Eastern Timezone	var eastern = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");\nvar local = TimeZoneInfo.Local; // PDT for me\nConsole.WriteLine(DateTime.Now.Add(eastern.BaseUtcOffset - local.BaseUtcOffset));	0
14374542	14354157	Make internal classes visible to others assemblies	[assembly: InternalsVisibleTo("LINQPadQuery")]	0
4919848	4919815	I want a script to show a string that I have declared	Page.ClientScript.RegisterStartupScript(Page.GetType(), \n             "message", \n             "window.alert("\'" + myString + "\'");",\n             true);	0
6067887	6062030	Run a Windows App using a specific User account	ProcessStartInfo psi = new ProcessStartInfo(myPath);\npsi.UserName = username;\n\nSecureString ss = new SecureString();\nforeach (char c in password)\n{\n ss.AppendChar(c);\n}\n\npsi.Password = ss;\npsi.UseShellExecute = false;\nProcess.Start(psi);	0
26265457	26079204	Save .mp4 to Windows Phone video library	var httpClient = new HttpClient();\nvar response = await httpClient.GetAsync(url);\n\nif (response.IsSuccessStatusCode)\n{\n    var file = await response.Content.ReadAsByteArrayAsync();\n    StorageFile destinationFile \n        = await KnownFolders.SavedPictures.CreateFileAsync("file.mp4",\n            CreationCollisionOption.ReplaceExisting);\n\n    Windows.Storage.Streams.IRandomAccessStream stream = await destinationFile.OpenAsync(FileAccessMode.ReadWrite);\n    IOutputStream output = stream.GetOutputStreamAt(0);\n\n    DataWriter writer = new DataWriter(output);\n    writer.WriteBytes(file);\n    await writer.StoreAsync();\n    await output.FlushAsync();\n}	0
19411117	19410511	show status pending to approve	CREATE PROCEDURE b\nAS\nSELECT  di.DocID, \n        di.DocName, \n        di.Uploadfile, \n        dt.DocType,\n        d.DepType, \n        at.ApproveType\nFROM    DocumentInfo di\n    JOIN\n        DocType dt ON dt.DocTypeID = di.DocTypeID\n    JOIN \n        Department d ON d.DepID = di.DepID\n    LEFT OUTER JOIN\n        Approval a ON a.DocID = di.DocID\n    JOIN\n        ApproveType at ON at.ApproveID = ISNULL(a.Approveid, 3)	0
28268520	27457917	Add Podcast feed to Podcast app programmatically	Launcher.LaunchUriAsync(new Uri("podcast:www.example.com/podcast.rss"));	0
7669568	7669527	How to detect if element exist using a lambda expression in c#?	XElement e = document.Element("myElement");\nif (e != null)\n{\n    var myValue = e.Value; \n}	0
18293528	18293227	How to find first and last cell in ExcelInterop and graph range in C#	var range = worksheet.get_Range("A1", System.Type.Missing).CurrentRegion;	0
21126279	21126222	WPF ListView Button Inherit Font Color	Foreground="{Binding Foreground, RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type ListViewItem}}}"	0
32505070	32504727	Read the file contents from all the files present in a specified folder	using System.IO;\n...\nforeach (string file in Directory.EnumerateFiles(folderPath, "*.*"))\n{\n    string contents = File.ReadAllText(file);\n}	0
6094634	6077801	how to achieve the same backgroud effect like the volume mixer?	var startColor = Color.FromArgb(241, 245, 251);\nvar endColor = Color.FromArgb(204, 217, 234);\n\nusing (var brGradient = new LinearGradientBrush(panel1.ClientRectangle, startColor, endColor, LinearGradientMode.Vertical))\n{\n    brGradient.Blend = new Blend\n            {\n                Factors = new[] { 1.0f, 0.1f, 0.0f },\n                Positions = new[] { 0.0f, 0.1f, 1.0f }\n            };\n    e.Graphics.FillRectangle(brGradient, panel1.ClientRectangle);\n}	0
3016577	3016522	Count the number of times a string appears within a string	Regex.Matches( input,  "true" ).Count	0
8606893	8606851	Check who a WinForm is running as	Application.Run	0
13278790	13276546	outlook vsto perform custom send message	if (this.Context is Outlook.Inspector)\n{\n    Outlook.Inspector oInsp = this.Context as Outlook.Inspector;\n    if (oInsp.CurrentItem is Outlook.MailItem)\n    {\n        Outlook.MailItem oMail = oInsp.CurrentItem as Outlook.MailItem;\n        ((Outlook._MailItem)oMail).Send();\n    }\n}	0
25654431	25654185	How can I update aspnet-scaffolding cshtml pages	Html.LabelForBootstrap	0
21412889	21412021	count the number of rows between two dates	SqlCommand command = new SqlCommand(@"SELECT StaffID, Name, sum(IsStaff), \n                                              sum(case when IsStaff = 1 then 0 else 1 end) \n                                               From TableName \n                                             WHERE Cast([Time] AS DATE) > @Time \n                                                 AND CAST([Time] AS DATE) < @Time2 \n                                             GROUP BY StaffID, Name\n                                             ORDER BY Time Desc", conn);	0
23415017	23414084	Creating a DataTable from a Linq query from a model passed in	var cl = new List<CancellationList>();\nvar dataTable = new DataTable();\nvar toObject = cl.Select(c => new object[] {c.SchemeId, c.EffectiveDate, c.TransactionDate, c.ExpiryDate});\ndataTable.Columns.Add("SchemeId", typeof (int));\ndataTable.Columns.Add("EffectiveDate", typeof (DateTime));\ndataTable.Columns.Add("TransactionDate", typeof(DateTime));\ndataTable.Columns.Add("ExpiryDate", typeof(DateTime));\nforeach (var data in toObject)\n{\n    dataTable.Rows.Add(data);\n}	0
9878774	9848878	Efficient approach for constant modification of text	private void richTextBox1_SelectionChanged(object sender, EventArgs e)\n{\n   LastCursorPosition = CurrentCursorPosition;\n   CurrentCursorPosition = richTextBox1.SelectionStart;\n   CursorsDifferences = CurrentCursorPosition - LastCursorPosition;\n\n}	0
22811366	22809992	Get the Treeview Parent From a TreeViewItem	public T ParentOfType<T>(DependencyObject element) where T : DependencyObject\n{\n    if (element == null)\n    return default (T);\n    else\n    return Enumerable.FirstOrDefault<T>(Enumerable.OfType<T>((IEnumerable) GetParents(element)));\n}\n\npublic IEnumerable<DependencyObject> GetParents( DependencyObject element)\n{\n    if (element == null)\n        throw new ArgumentNullException("element");\n    while ((element = GetParent(element)) != null)\n        yield return element;\n}\n\nprivate DependencyObject GetParent(DependencyObject element)\n{\n    DependencyObject parent = VisualTreeHelper.GetParent(element);\n    if (parent == null)\n    {\n        FrameworkElement frameworkElement = element as FrameworkElement;\n        if (frameworkElement != null)\n            parent = frameworkElement.Parent;\n    }\n    return parent;\n}	0
4667582	4659215	How to get status of socket when network cable disconnect from network adapter	uint dummy = 0;\n    byte[] inOptionValues = new byte[Marshal.SizeOf(dummy) * 3];\n    //set keepalive on\n    BitConverter.GetBytes((uint)1).CopyTo(inOptionValues, 0); \n    //interval time between last operation on socket and first checking. example:5000ms=5s\n    BitConverter.GetBytes((uint)5000).CopyTo(inOptionValues, Marshal.SizeOf(dummy));\n    //after first checking, socket will check serval times by 1000ms.\n    BitConverter.GetBytes((uint)1000).CopyTo(inOptionValues, Marshal.SizeOf(dummy) * 2);\n\n    Socket socket = __Client.Client;\n    socket.IOControl(IOControlCode.KeepAliveValues, inOptionValues, null);	0
1540475	1540384	Consuming Custom Attributes	public void Validate( object obj )\n {\n       foreach (var property in obj.GetType().GetProperties())\n       {\n            var attribute = property.GetCustomAttributes(typeof(ValidationAttribute), false);\n            var validator = ValidationFactory.GetValidator( attribute );\n            validator.Validate( property.GetValue( obj, null ) );\n       }\n }	0
22427198	22427150	Remove InternalsVisibleTo for production	#if(DEBUG)\n[assembly:InternalsVisibleTo("SomeAssembly")]\n#endif	0
2246000	2245938	How do I return a method paramenter with RedirectToAction	return RedirectToAction("Edit", new { failed = true });	0
33802851	33802676	How to get a raw memory pointer to a managed class?	GCHandle gcHandle = GCHandle.Alloc(yourObject,GCHandleType.WeakTrackResurrection);\nIntPtr thePointer = GCHandle.ToIntPtr(gcHandle);	0
6713187	6712984	Automatically generating code from a text or xml file and then compiling?	>>> from xml.etree import ElementTree as etree\n>>> corpus = '''<category1>\n...       <subcategory>\n...         entry1\n...         entry2\n...       </subcategory>\n... </category1>\n... '''\n>>> doc = etree.fromstring(corpus)\n>>> for subcategory in doc.getchildren():\n...     for entry in filter(bool,\n...                         map(str.strip,\n...                             subcategory.text.split('\n'))):\n...         print "entry output: (%s)" % entry\n...     print "subcategory output (%s)" % subcategory.tag\n... \nentry output: (entry1)\nentry output: (entry2)\nsubcategory output (subcategory)\n>>>	0
1305398	1305214	c# return resultset from Oracle store procedure and fill a DataTable	create or replace\nPROCEDURE  SP_GET_TBL (o_rc OUT sys_refcursor) AS\n   open o_rc for\n        select Col1, Col2, Col3 from Tbl;\nEND SP_GET_TBL;	0
18036395	18036220	How do i use folderbrowserdialog?	using (FolderBrowserDialog dialog = new FolderBrowserDialog())\n{\n    if (dialog.ShowDialog() == DialogResult.OK)\n    {\n        string path = dialog.SelectedPath;\n    }\n}	0
11841081	11824967	How to use NpgsqlCopyIn with NpgsqlCopySerializer?	NpgsqlConnection Conn = new NpgsqlConnection(getPostgresConnString());\nConn.Open();\nNpgsqlCopyIn copyIn = new NpgsqlCopyIn("COPY table  (col1,col2,col2)   FROM STDIN;", Conn);\ncopyIn.Start();\nNpgsqlCopySerializer cs1 = new NpgsqlCopySerializer(pConn2);\ncs1.AddString(System.IO.File.ReadAllText("C:\\test\\Web.config"));\n[...]\ncs1.EndRow();\ncs1.Close();\ncopyIn.End();	0
8063009	8062954	Linq: Find Element in a Collection	Albums.SelectMany(a=>a.Songs).FirstOrDefault(song => song.Id == id)	0
4270114	4270090	Getting the domain from a URL encoded string	(new URI(System.Web.HttpServerUtility.UrlDecode(url))).Host	0
24158246	24158079	Returning image to android app from WCF REST using JSON	Bitmap  image =BitmapFactory.decodeStream(response.getEntity().getContent())	0
23883609	23883512	Is there a way to do the following with XmlSerializer?	[XmlAttribute("Name")]\npublic string Name {get;set;}\n\n[XmlElement("Name")]\npublic string NameAlt {\n    get { return Name; }\n    set { Name = value; }\n}\n// to prevent serialization (doesn't affect deserialization)\npublic bool ShouldSerializeNameAlt() { return false; }	0
7579261	7579184	Starting a service	void OnStart(string[] args)	0
29605625	29605166	How to replace an XElement value without changing the encoding	section.ReplaceWith(XElement.Parse(replacementString);	0
11034843	10930616	Silverlight Webpart get list items	foreach (ListItem listItem in listItems)\n   {\n     textBox1.Text += listItem.FieldValues["File_x0020_Type"].ToString();\n   }	0
3140385	3140288	How to delete specific nodes from an XML file using LINQ in C#	XDocument X_DOC = XDocument.Load(Application.StartupPath + "\\Sample.xml");\n        X_DOC.Root.Elements("Child").Remove();\n        X_DOC.Save(Application.StartupPath + "\\Sample.xml");	0
22832586	22832270	Silverlight childwindow closing after timestamp is over	DispatcherTimer idleTimer;\n    DateTime timeNow;\n    public ChildWindow1()\n    {\n        InitializeComponent();\n\n        idleTimer = new DispatcherTimer();\n        idleTimer.Start();\n        idleTimer.Interval = TimeSpan.FromSeconds(1);\n\n        idleTimer.Tick += new EventHandler(idleTimer_Tick);\n        timeNow= DateTime.Now;\n        // Initialise last activity time\n    }\n\n    private void OKButton_Click(object sender, RoutedEventArgs e)\n    {\n        this.DialogResult = true;\n    }\n\n    private void CancelButton_Click(object sender, RoutedEventArgs e)\n    {\n        this.DialogResult = false;\n    }\n    private void idleTimer_Tick(object sender, EventArgs e)\n    {\n        if (DateTime.Now > timeNow.AddSeconds(30))\n        {\n            this.Close();\n        }\n    }	0
4088713	4088660	control desktop maximize area in C#	public partial class MyForm : Form\n{\n    public MyForm()\n    {\n        InitializeComponent();\n\n        // set width to 1/2 of screen\n        Rectangle screenBounds = Screen.PrimaryScreen.Bounds;\n        screenBounds.Width = screenBounds.Width / 2;            \n        this.MaximizedBounds = screenBounds;\n\n        // maximize\n        this.WindowState = FormWindowState.Maximized;\n    }\n}	0
7582200	7581808	How to efficiently prune a list based on "is-subset" condition?	var sets = testResult\n.Select(x => new { Key = x.Key, Set = new HashSet<int>(x.Value.Concat(new[] { x.Key })) })\n.ToList();\nvar res = sets.Where(s => sets.Any(x => x.Set.IsSupersetOf(s.Set) && x.Key != s.Key));\nvar keysToRemove = res.Select(x => x.Key);	0
29258486	29255952	Kendo DropDownList too slow while read dataSource	Html.Kendo().ComboBoxFor(m => m.ObjectID)\n                    //start autocompleting only after 3 char\n                    .MinLength(3)	0
33136332	33136163	C# - How to get variables from a different method?	class ContainingClass\n{\n    int randomNumber;\n    int randomNumber2;\n\n    public void generateNumbers()\n    {\n        Random rand = new Random();\n        randomNumber = rand.Next(1, 11);\n        randomNumber2 = rand.Next(1, 11);\n        Console.WriteLine("Number1: " + randomNumber);\n        Console.WriteLine("Number2: " + randomNumber2);\n    }\n\n    public int findSum()\n    {\n        return randomNumber + randomNumber2; //gets sum from the method generateNumbers()\n    }\n}	0
8124632	8041288	Opening two ribbons with one load for excel 2010 with c#	[ComVisible(true)]\n[ComDefaultInterface(typeof(IBackStageInfo))]	0
1639650	1609272	Get write access to local_machine\software in the registry for .net application	Process.Start("edit.reg")	0
18486697	18485904	local bitmapimage(windows phone)	FlagImage.Source = new BitmapImage(new Uri("/images/sky.jpg", UriKind.Relative));	0
19495353	19495255	How to pass multiple data between pages in windows phone	NavigationService.Navigate(new Uri("/Page.xaml?object1="+obj+"&object2="+obj2, UriKind.Relative));	0
22717563	22694672	Get blendshapes by name rather than by index	public string [] getBlendShapeNames (GameObject obj)\n{\n    SkinnedMeshRenderer head = obj.GetComponent<SkinnedMeshRenderer>();\n    Mesh m = head.sharedMesh;\n    string[] arr;\n    arr = new string [m.blendShapeCount];\n    for (int i= 0; i < m.blendShapeCount; i++)\n    {\n      string s = m.GetBlendShapeName(i);\n      print("Blend Shape: " + i + " " + s);\n      arr[i] = s;\n    }\n    return arr;\n}	0
2327204	2327188	How can I add a namespace in C# Express 2008?	namespace XXX.YYY.ZZZ\n{\n    /* your types that go in that namespace */\n}	0
29791621	29791289	Use Linq Where on child entity in lambda expression?	public IEnumerable<UserProperty> GetSearches(int userId)\n{\n    return userRepository.Where(x => x.Id == userId).Select(x => x.Properties.Where(p => p.IsActive)).Single(); //I assumed userId is unique\n}	0
17430500	17406873	Get Word ML from clipboard	D0 CF 11 E0 A1 B1 1A E1	0
20583603	20583460	How to create an Expression that invokes (or is combined with) another Expression using a closure object as argument?	public void DoSomethingUsingExpressionWithArgument(Expression<Func<SomeClass, bool>> expressionWithArgument)\n{\n    var thisExpr = Expression.Constant(this);\n    var pExpr = Expression.Property(thisExpr, "SomeProperty");\n    var invokeExpr = Expression.Invoke(expressionWithArgument, pExpr);\n    Expression<Func<bool>> expressionWithoutArgument = Expression.Lambda<Func<bool>>(invokeExpr);\n    DoSomethingUsingExpressionWithoutArgument(expressionWithoutArgument);\n}	0
10970975	10970841	ContextMenuStrip for wrong item in TreeView	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {\n    if (e.Button == MouseButtons.Right) {\n        treeView1.SelectedNode = e.Node;\n        contextMenuStrip1.Show(treeView1, e.Location);\n    }\n}	0
6317755	6317629	Win phone 7 read XML file	foreach (XElement cookie in appDataXml.Elements())\n{\n    ViewModels.Cookie tempCookie = new ViewModels.Cookie();\n    tempCookie.Name = cookie.Element("Name").Value;\n\n    _cookieList.Add(tempCookie);\n}	0
29447161	29443717	String was not recognized as Valid Datetime	if (txtdol.Text == null || txtdol.Text == string.Empty)\n                        {\n                            cmd.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = DBNull.Value;\n                        }\n                        else\n                        {\n                            cmd.Parameters.Add("@leaving_date", SqlDbType.DateTime).Value = Convert.ToDateTime(txtdol.Text);\n                        }	0
26556386	26556340	Get the first displayed row of datagridview	DataGridView.FirstDisplayedScrollingRowIndex	0
31654878	31654629	search a character from string and store all data into a variable before that char	var before = "http://abc/abc_UAT/CustomerDetail.aspx?r=1";\nvar wantedString = before.Split('?')[0];	0
34417764	34357172	DetailsView - Values not changing in ItemUpdating	protected void Page_Load(object sender, EventArgs e)\n{\n    if (!IsPostBack)\n    {\n        using (var context = new CustomersContext())\n        {\n            customer = context.Logins.First();\n        }\n\n        CustomerDetailsView.DataSource = new List<Customer>() { customer };\n        CustomerDetailsView.DataBind();\n    }\n}	0
12515016	12324154	How to provide validation for child classes that implement different properties?	protected void Validate(string propertyName, string propertyValue, List<ValidRule> validRules) {\n      string temp = propertyValue.ToString();\n      this.RemoveError(propertyName);\n      if(propertyName.Equals("Description")) {\n           foreach(ValidRule validRule in validRules) {\n                if(!Regex.IsMatch(propertyValue, validRule.Rule) && !String.IsNullOrWhiteSpace(propertyValue)) {\n                     this.AddError(propertyName, validRule.ErrorMessage);\n                     break;\n                }\n           }\n      }\n }	0
20031383	20031363	How can I filter a collection so I get only the rows where the value of a fields is not null?	_questionService.GetData().Where(x => x.text != null);	0
25611892	25611703	Using For loop Int in DataGridView.Rows[]	string[] Array1 = new string[3];   \n\n                for (int i = 0; i < dataGridView1.Rows.Count; i +=1)\n                {\n                    Array1 [0] = dataGridView1.Rows[i].Cells[0].Value.ToString();\n                    Array1 [1] = dataGridView1.Rows[i].Cells[1].Value.ToString();\n                    Array1 [2] = dataGridView1.Rows[i].Cells[2].Value.ToString();\n                }	0
6549902	6549886	Problem with Index of in Substring array	string[] substrings = inputString.Split("#$%");	0
9281890	9281861	arrange students in descending order	public ActionResult Index()\n{    \n  return View(_repository.ListAll().OrderByDescending(s => s.Name));\n}	0
3253147	3252800	how to pass sql parameter as null value in integer datatype variable?	else\n    {\n        sBO.Client_id = System.Data.SqlTypes.SqlInt32.Null;\n    }	0
27330633	27329219	how to get values from xml response	var xd = XDocument.Parse(xml);\n        var modemResponse = xd.Element("controls").Element("ModemResponse").Value;\n        string address = string.Empty, netmask = string.Empty;\n        var tokens = modemResponse.Split(new[] { ' ', '=' }, StringSplitOptions.RemoveEmptyEntries);\n        for (int i = 0; i < tokens.Length; i++)\n        {\n            var token = tokens[i];\n            switch (token)\n            {\n                case "address":\n                    if (i + 1 < token.Length)\n                        address = tokens[i + 1];\n                    break;\n                case "netmask":\n                    if (i+1 < tokens.Length)\n                        netmask = tokens[i+1];\n                    break;\n            }\n        }\n\n        Console.WriteLine("address: {0}, netmask: {1}", address, netmask);	0
10999509	10999232	How do I split imported XML points into separate groups?	XElement root = XElement.Load(file); // or .Parse(string)\nvar lines = root.Descendants("LINE")\n    .Select(line =>\n        new\n        {\n            Id = (string)line.Element("ID"),\n            Points = line.Elements("POINT")\n                .Select(p => new PointF\n                {\n                    X = (float)p.Attribute("X"),\n                    Y = (float)p.Attribute("Y")\n                }).ToArray()\n        }).ToArray();	0
12290905	12290872	How do I close an open file?	Process myProcess;\n\nprivate void btnViewErrorLogFile_Click(object sender, EventArgs e)\n{\n    myProcess.Start(AppVars.ErrorLogFilePath);\n}\n\nprivate void doSomething()\n{\n    if (!myProcess.HasExited)\n    {\n      myProcess.CloseMainWindow();\n      myProcess.Close();\n    }\n\n    // Do whatever you need with the file\n}	0
7174680	7174576	Check for the result of a query	DbCommand.ExecuteNonQuery	0
22859978	22781214	Telerik radgird show column sum in footer in rad grid depend on other column	var sumEur = yourtable.compute("sum(Price)",CurrencyCode='GBP');\nvar sumGBP = yourtable.compute("sum(Price)",CurrencyCode='EUR');\nvar sumUSD = yourtable.compute("sum(Price)",CurrencyCode='USD');	0
94078	93983	How can I split a string using regex to return a list of values?	private void RegexTest()\n    {\n        String input = "foo[]=1&foo[]=5&foo[]=2";\n        String pattern = @"foo\[\]=(\d+)";\n\n        Regex regex = new Regex(pattern);\n\n        foreach (Match match in regex.Matches(input))\n        {\n            Console.Out.WriteLine(match.Groups[1]);\n        }\n    }	0
7592711	7592696	Count folder inside the folder	System.IO.DirectoryInfo()	0
7974576	7961269	How To Update an Excel File From a Gridview Row in ASP.NET (C#)?	using (DbCommand command = oledbConn.CreateCommand())\n{\n    command.CommandText = "INSERT INTO [Sheet2$] (custid, Fullname, Salutation) VALUES (" + CustID + ",\"John Smith\",\"John\")";\n\n    //connection.Open();\n\n    command.ExecuteNonQuery();\n}	0
9751041	9750853	How to read very long input from console in C#?	StringBuilder sb =new StringBuilder();\n        while (true) {\n            char ch = Convert.ToChar(Console.Read());\n            sb.Append(ch);\n            if (ch=='\n') {\n                break;\n            }\n        }	0
24064673	24059238	How to retain values from a textbox after page load in sharepoint 2010?	JSRequest.EnsureSetup();\nvar sfield = JSRequest.QueryString["cs"];\nvar tbSearch = JSRequest.QueryString["tb"];\n\ndocument.getElementById('sfield').value = sfield;\ndocument.getElementById('tbSearch').value = tbSearch;	0
4632546	4632050	Stub the behavior of a readOnly property	int count = 0;\n\n    var mock = MockRepository.GenerateStub<ICell>();\n    mock.Stub(p => p.Value).WhenCalled(a => a.ReturnValue = count).Return(42);\n    mock.Stub(p => p.IncrementValue()).WhenCalled(a => {\n        count = (int)count+1; \n    });	0
28633046	28632955	Replace All char in a string of an object in a list c#	classes = classes\n    .Select(c => {\n        c.code = new string('X', c.code.Length - 4) + c.code.Substring(c.code.length - 4);\n        return c;\n    })\n    .ToList();	0
12189853	12188029	How do I send messages from server to client using SignalR Hubs	void aTimer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n    {\n        var context = GlobalHost.ConnectionManager.GetHubContext<Chat>();\n        context.Clients.All.addMessage("Hello");      \n    }	0
28018973	28018615	Commandbar in Windows Phone 8.1	CommandBar CommandBarObject = new CommandBar();\n AppBarButton FirstBtn = new AppBarButton() { Icon = new BitmapIcon() { UriSource = new Uri("ms-appx:///Assets/first.png") } };\n FirstBtn.Label = "First";\n FirstBtn.Click += FirstBtn_Click;\n FirstBtn.IsEnabled = true;\n\n AppBarButton secondaryCommand = new AppBarButton() { Label = "Second", IsEnabled = true } };\n secondaryCommand.Click += FirstBtn_Click;\n\n CommandBarObject.PrimaryCommands.Add(FirstBtn);\n CommandBarObject.SecondaryCommands.Add(secondaryCommand);	0
23175257	23174662	DataGrid Date String Filter	DateTime temp;\n// try to parse the provided string in order to convert it to datetime\n// if the conversion succeeds, then build the dateFilter\nif(DateTime.TryParse(TrystartDate.Text, out temp))\n{\n    string dateFilter = temp.ToString("dd/MM/yyyy");\n    var filteredList = images.Where(item => item.Date == dateFilter);\n    var filterSource = new BindingSource();\n    filterSource.DataSource = filteredList;\n    navigationGrid.DataSource = filterSource;\n}	0
2665342	2665325	How to add SQLite (SQLite.NET) to my C# project	.\Dev\DataFeed	0
1919092	1919083	How to clear a TextBox?	private void buttonSend_Click(object sender, EventArgs e)\n{\n    // send text\n    byte[] outStream = System.Text.Encoding.ASCII.GetBytes(textSend.Text + "$");\n    serverStream.Write(outStream, 0, outStream.Length);\n    serverStream.Flush();\n\n    // clear textbox\n    textSend.Text = "";\n}	0
7754865	7754828	Maintaining 60 elements in a observablecollection	if (Power.Count == 60)\n    Power.RemoveAt(0);\n\nPower.Add(new KeyValuePair<double, double>(i, SolarCellPower ));	0
25477686	25476497	Retrieving Office.customeXMLparts without namespaces	//*[local-name()='SoftwareName']\n   /*[local-name()='Settings']\n   /*[local-name()='FormPassword']	0
7373010	7372947	C# - Terminating Application.Run()	ApplicationContext threadContext;\n\n    private void startLoop() {\n        threadContext = new ApplicationContext();\n        var messageLoop = new Thread(() => Application.Run(threadContext));\n        messageLoop.Start();\n    }\n\n    private void stopLoop() {\n        threadContext.ExitThread();\n        threadContext = null;\n    }	0
20668138	20668029	Replacing non-alphabet characters in a string	Regex rgx = new Regex("[^a-zA-Z -]");\nstr = rgx.Replace(str, " ");	0
14682239	14682077	How to call second target in Msbuild	%SystemRoot%\Microsoft.NET\Framework\v4.0.30319\MSBuild.exe "D:\test_2\MsBuild\MsBuild\BuildScript\MsBuild.csproj" /t:SecondTarget	0
20670677	20670557	Entity Framework Combining Strings	public string CombinedProperty\n{\n    get\n    {\n        return String.Format("{0}\n{1}\n{2}", leadTag, content, EndTag);\n    }\n}	0
4448682	4447909	How to clear microsoft ink picture control?	inkPicture1.InkEnabled = false;\ninkPicture1.Ink = new Microsoft.Ink.Ink();\ninkPicture1.InkEnabled = true;\ninkPicture1.Invalidate();	0
5529679	5521896	How to maintain selected row of XtraGrid control	public EditForm(Point location, GridColumnCollection columns, object dataSource, BindingContext context)\n            : this() {\n            StartPosition = FormStartPosition.Manual;\n            Location = location;\n            BindingContext = context;  // <<<<<<\n            allowTrackValueChanges = false;\n            this.dataSource = dataSource;\n...\n}	0
17827246	17827017	Validating string value has the correct XML format	string parameter="<HostName>Arasanalu</HostName><AdminUserName>Administrator</AdminUserName><AdminPassword>A1234</AdminPassword><PlaceNumber>38</PlaceNumber>";\nXmlDocument doc = new XmlDocument(); \\ndoc.LoadXml("<root>" + parameter + "</root>"); // this adds a root element and makes it Valid	0
1501583	1501577	Change CSS Dynamically	protected void Page_Init(object sender, EventArgs e)\n    {\n        HtmlLink css = new HtmlLink();\n        css.Href = "css/fancyforms.css";\n        css.Attributes["rel"] = "stylesheet";\n        css.Attributes["type"] = "text/css";\n        css.Attributes["media"] = "all";\n        Page.Header.Controls.Add(css);\n    }	0
16737164	16736785	Create temp table with stored procedure on page load	using (var con = new SqlConnection(cs))	0
1131204	1131184	C#: Initializing an event handler with a dummy	protected void OnPropertyChanged(string propertyName)\n{\n    PropertyChangedEventHandler handler;\n    lock (propertyChangedLock)\n    {\n        handler = propertyChanged;\n    }\n    handler(this, new PropertyChangedEventArgs(propertyName));\n}	0
20953192	20953027	A method to send multiple "key":"value" pairs in JSON	public class Request\n{\n    public string request { get; set; }\n    public IDictionary<string,string> parameters { get; set; }\n    public string pid { get; set; }\n}\n\n\nvar request = JsonConvert.DeserializeObject<Request>(data);	0
7575717	7561456	XML StringWriter empty	flush()	0
10452552	10452394	Is there a more efficient way of creating a list based on an existing list and a lookup list?	private IEnumerable<DataPoint> GetHistorianDatapoints(IEnumerable<DataPoint> fileDatapoints, IEnumerable<Tagname> historianTagnames)\n{\n    var tagNameDictionary = historianTagnames.ToDictionary(t => t.DataLoggerTagname, StringComparer.OrdinalIgnoreCase);\n\n    foreach (var fileDatapoint in fileDatapoints)\n    {                \n        if (tagNameDictionary.ContainsKey(fileDatapoint.Name))\n        {\n            var historianTagname = tagNameDictionary[fileDatapoint.Name];\n            var historianDatapoint = new DataPoint();\n\n            historianDatapoint.Name = historianTagname.HistorianTagname;\n            historianDatapoint.Date = fileDatapoint.Date;\n            historianDatapoint.Value = fileDatapoint.Value;\n\n            yield return historianDatapoint;\n        }\n    }\n}	0
13558157	13557942	How to set combox item visibility?	private void comboboxA_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    for (int i = 0; i <= comboboxB.Items.Count -1; i++)\n    {\n        if (((ComboBoxItem)(comboboxB.Items[i])).Content.ToString() == ((ComboBoxItem)comboboxA.SelectedItem).Content.ToString())\n        {\n            ((ComboBoxItem)(comboboxB.Items[i])).Visibility = System.Windows.Visibility.Collapsed;\n        }\n        else\n            ((ComboBoxItem)(comboboxB.Items[i])).Visibility = System.Windows.Visibility.Visible;\n    }\n}	0
30917202	30917056	How to do validation for list of emails in C#	foreach (SmtpRequestContent email in emails)\n{\n    YourValidateMethod(email);\n}	0
28368125	28367374	How to add HTML elements Dynamically (ASP.NET)	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Web;\nusing System.Web.UI;\nusing System.Web.UI.HtmlControls;\nusing System.Web.UI.WebControls;\n\npublic partial class _Default : System.Web.UI.Page\n{\n    protected void Page_Load(object sender, EventArgs e)\n    {\n        for (int i = 1; i < 11; i++)\n        {\n            LinkButton linkButton = new LinkButton();\n            linkButton.Text = "Lnk" + i;\n            linkButton.Click += linkButton_Click;\n            form1.Controls.Add(linkButton);\n\n            HtmlGenericControl p = new HtmlGenericControl("p");\n            p.InnerText = "Separator";\n            form1.Controls.Add(p);\n        }\n    }\n\n    void linkButton_Click(object sender, EventArgs e)\n    {\n        Response.Redirect("http://www.stackoverflow.com");\n    }\n}	0
5037006	5028727	Is there a fluent email library for c#?	var email = Email\n            .From("john@email.com")\n            .To("bob@email.com", "bob")\n            .Subject("hows it going bob")\n            .UsingTemplate(@"C:\Emailer\TransactionTemplate.htm")\n            .Replace("<%CurrentDate%>", DateTime.Now.ToShortDateString())\n            .Replace("<%FullName%>", fullName)\n            .Replace("<%SaleDate%>", saleDate)	0
9239691	9236070	Casting a member access func from Func<DerivedFromT,object> to Func<T,object>	Map(x => ((ICategorizedEntity)x).Category);	0
24090306	24090266	C# - Remove Beginning of String then Splitting by a delimiter	string delimiterString = numbers.Substring(2, 1);\nchar delimiter = delimiterString[0];\nstring resultSource = numbers.Remove(0, 5);\nstring[] result = resultSource.Split(delimiter);	0
16390502	16389224	Set Window almost Topmost	public MainWindow() {\n        InitializeComponent();\n        this.WindowState = System.Windows.WindowState.Maximized;\n        this.ResizeMode = System.Windows.ResizeMode.NoResize;\n    }	0
24357672	24347619	Switch active view between two Revit Documents	public Result Execute(ExternalCommandData cmdData, ref string message, ElementSet elements)\n{\n    UIDocument uiDoc = cmdData.Application.OpenAndActivateDocument(@"c:\project.rvt");\n    // do stuff with uiDoc\n\n    return Result.Succeeded;\n}	0
25136482	25136382	C# transform string to date yyyy-MMM	string Input = "june 2014";\nDateTime dt;\nDateTime.TryParseExact(Input.ToString(), "MMMM yyyy",\n                       CultureInfo.InvariantCulture, DateTimeStyles.None, out dt);\nConsole.WriteLine(dt.ToString("yyyy-MM"));	0
2242408	2242348	quick-and-dirty way to pass a method with parameters, as a parameter?	public delegate void QueuedMethod();\n\nstatic void Main(string[] args)\n{\n    methodQueue(delegate(){methodOne( 1, 2 );});\n    methodQueue(delegate(){methodTwo( 3, 4 );});\n}\n\nstatic void methodOne (int x, int y)\n{\n\n}\n\nstatic void methodQueue (QueuedMethod parameter)\n{\n    parameter(); //run the method\n    //...wait\n    //...execute the parameter statement\n}	0
3294750	3294620	How to send generated pdf file as attachment in email from C#?	MemoryStream ms = new MemoryStream(fileContentResult.FileContents); \n// Create an in-memory System.IO.Stream\n\nContentType ct = new ContentType(fileContentResult.ContentType);\n\nAttachment a = new Attachment(ms, ct);	0
11906310	11906269	Using Parameters in LINQ	XElement books = XElement.Load(@"Friends.xml");\nstring yourDate = "27";\nstring yourMonth = "05";\n\nvar titles =\n   from book in books.Elements("Friend")\n   where (string)book.Element("Date") == yourDate  && (string)book.Element("Month") == yourMonth\n   select book.Element("Name");\n\nforeach (var title in titles)\n   Console.WriteLine(title.Value);	0
23086136	23085943	c# - how to best save and load an enum	var myValue = MyEnum.Value3;\n\n    var stringRepresentation = myValue.ToString();\n    var intRepresentation = (int)myValue;\n\n    Console.WriteLine("String-Value: \"{0}\"", stringRepresentation);\n    Console.WriteLine("Int-Value: {0}", intRepresentation);\n\n    var parsedFromString = (MyEnum)Enum.Parse(typeof(MyEnum), stringRepresentation);\n    var parsedFromInt = (MyEnum)Enum.Parse(typeof(MyEnum), intRepresentation.ToString());\n\n    Console.WriteLine("Parsed from string: {0}", parsedFromString);\n    Console.WriteLine("Parsed from int: {0}", parsedFromInt);	0
10555124	10554899	IPC in C#, sending text from one exe to another exe	[DllImport("user32.dll", EntryPoint = "FindWindowEx")]\npublic static extern IntPtr FindWindowEx(IntPtr hwndParent, IntPtr hwndChildAfter, string lpszClass, string lpszWindow);\n\n[DllImport("User32.dll")]\npublic static extern int SendMessage(IntPtr hWnd, int uMsg, int wParam, string lParam);\n\nprivate static void DoSendMessage(string message)\n{\n    Process notepad = Process.Start(new ProcessStartInfo("notepad.exe"));\n    notepad.WaitForInputIdle();\n\n    if (notepad != null)\n    {\n        IntPtr child = FindWindowEx(notepad.MainWindowHandle, new IntPtr(0), "Edit", null);\n        SendMessage(child, 0x000C, 0, message);\n    }\n}	0
1054319	1053979	How to programmatically set parameters for EntityDataSource and DetailsView?	Parameter parameter = new Parameter("MyParam", TypeCode.String,\n    Page.User.ProviderUserKey);\nMyDataSource.SelectParameters.Add(parameter);	0
17980905	17980302	How to keep border on a fixed form?	// run in LINQpad\nprivate const int GWL_STYLE = -16;\nprivate const int WS_SIZEBOX = 0x040000;\n[DllImport("user32.dll", SetLastError = true)]\nprivate static extern int GetWindowLong(IntPtr hWnd, int nIndex);\n[DllImport("user32.dll")]\nprivate static extern int SetWindowLong(IntPtr hWnd, int nIndex, int dwNewLong);\nvoid Main()\n{\n    var form = new Form();\n    form.ControlBox = false;\n    form.FormBorderStyle = FormBorderStyle.FixedDialog;\n    form.Show();\n    SetWindowLong(form.Handle, GWL_STYLE, GetWindowLong(form.Handle, GWL_STYLE) | WS_SIZEBOX);\n}	0
21229794	21229651	Add a specific function of a program to Windows Context Menu	class Program\n{\n    [STAThread]\n    public static void Main(string[] args)\n    {\n        if (runNormally(args))\n        {\n            MainWindow mainWindow = new MainWindow();\n            var app = new Application();\n            app.Run(mainWindow);\n        }\n        else\n        {\n            MyFunction(args);\n        }\n    }\n}	0
911317	899741	Logging WCF message sizes	Public Function AfterReceiveRequest(ByRef request As System.ServiceModel.Channels.Message, ByVal channel As System.ServiceModel.IClientChannel, ByVal instanceContext As System.ServiceModel.InstanceContext) As Object Implements System.ServiceModel.Dispatcher.IDispatchMessageInspector.AfterReceiveRequest\n    'Output the request message to immediate window\n    System.Diagnostics.Debug.WriteLine("*** SERVER - RECEIVED REQUEST ***")\n    System.Diagnostics.Debug.WriteLine(request.ToString())\n\n    Return Nothing\nEnd Function	0
12739393	12739243	Populating x and y coordinates from textfile values (Game of Life- Logic)	while (infile.Peek() >= 0) \n {\n     string[] values = infile.ReadLine().Split(' ');\n     fill_in[int.Parse(values[0]), int.Parse(values[1])] = true;\n }	0
13519268	13519167	Can derived C# interface properties override base interface properties with the same name?	public class RandomWife : Wife // implementing the Wife interface\n\n    {\n        private RandomHusband husband;\n        public Husband darling { get { return husband; } set { husband = value; } }\n        public Man  Wife.darling { get { return husband; } set { /* can't set anything */ } }\n\n    }	0
21678584	21678504	Take Negation of Func<double[], double[]>	using System.Linq;    \n\nFunc<double[], double[]> oldFunc = this.Gradient;\nthis.Gradient = (x) => oldFunc(x).Select( y => -y).ToArray();	0
4799769	4799738	Pass Type as a parameter to a function	var c = (BaseClass)Activator.CreateInstance(dict["type1"]);	0
5711062	5711027	replacing a hardcoded path	string antcbatchpath = string.Format(@"""C:\Work\{0}\release\SASE Lab Tools\ANT Builds\antc.bat""", buildStream);	0
20051182	20050142	Export datatable to pdf with more then 100 columns in dt	Rectangle method:\n\n      Document document = new Document(new Rectangle(200f, 300f)); \nPageSize method: \n      Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);\n\nPdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));\n\n    document.Open();\n    document.Add(new Paragraph("Welcome to dotnetfox"));\n    document.Close();	0
5303602	5302935	How to get the signed_request via the Facebook c# SDK	dynamic data = CanvasContext.Current.SignedRequest.Data\nif (data.page.liked) {\n // has liked\n} else {\n // Not liked\n}	0
12903681	12805345	Send combination of keystrokes to background window	class SendMessage\n{\n[DllImport("user32.dll")]\npublic static extern IntPtr PostMessage(IntPtr hWnd, uint Msg, IntPtr wParam, IntPtr lParam);\n\npublic static void sendKeystroke()\n{\n    const uint WM_KEYDOWN = 0x100;\n    const uint WM_KEYUP = 0x0101;\n\n    IntPtr hWnd;\n    string processName = "putty";\n    Process[] processList = Process.GetProcesses();\n\n    foreach (Process P in processList)\n    {\n        if (P.ProcessName.Equals(processName))\n        {\n            IntPtr edit = P.MainWindowHandle;\n            PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.Control), IntPtr.Zero);\n            PostMessage(edit, WM_KEYDOWN, (IntPtr)(Keys.A), IntPtr.Zero);\n            PostMessage(edit, WM_KEYUP, (IntPtr)(Keys.Control), IntPtr.Zero);\n        }\n    }                           \n}\n\n}	0
9064761	9064597	Get String before/after String.indexof in c#	var snippet = //your text here.\n var rawXml = "<text>" + snippet + "</text>"; // Wrap to make valid XML.\n XmlDocument xmlDoc = new XmlDocument();\n xmlDoc.LoadXml(rawXml);\n var mergedText = xmlDoc.InnerText;\n int start = mergedText.IndexOf(startMarker);\n int end = mergedText.IndexOf(endMarker) - start;\n mergedText.Substring(start, end);	0
8905141	8904453	One instance of control sharing property with another?	new PropertyMetadata(new List<UIElement>()	0
2857095	2857064	how can i convert a video into image files using ffmpeg in c#?	foo-001.jpeg',	0
16890281	16890225	Some advice on program performance	System.Web	0
25396461	25396414	Is there a way to merge a collection of duplicated items along with their child collections using LINQ?	var output = from p in input\n             group p by p.Id into g\n             select new Pallet\n             {\n                 Id = g.Key,\n                 Locations = (from l in g.SelectMany(x => x.Locations)\n                              group l by l.Id into gl\n                              select new Location { Id = gl.Key }).ToList()\n             };	0
2934685	2934675	Jointure in linq with a regular expression	from i in collectiona\nfrom j in collectionb\nwhere Regex.IsMatch(i.name, j.jokered_name)\nselect ...	0
26181253	26180869	How to get values from multiple textboxes at once?	An object reference is required for the non-static field, method, or property	0
14830050	14829997	split a string and use each item to assign to another list	var userRoles = new List<Roles>();\n\nforeach(var role in listRoles.Split(";"))\n{\n   userRoles.Add(listRoles.First(x => x.RoleName == role))\n}	0
10307170	10306983	How can I load SQL data source from a TextBox in C#?	string x = nastavenia.adresa_servera().Replace("\\", "\");	0
18708780	18707366	ASP.NET Routing - How to respond 404 for .aspx requests	routes.RouteExistingFiles = true;\nroutes.MapPageRoute("Route1", "Pages/{page}.aspx", "~/404.aspx");\nroutes.MapPageRoute("Route2", "Pages/{folder}/{page}.aspx", "~/404.aspx");	0
3906665	3905696	Setting DropDown list width of DataGridView ComboBoxColumn - WinForms	// This line is picked up from designer file for reference\n  DataGridViewComboBoxColumn CustomerColumn; \n\n  DataTable _customersDataTable = GetCustomers();\n\n  CustomerColumn.DataSource = _customersDataTable;\n  CustomerColumn.DisplayMember = Customer_Name;\n  CustomerColumn.ValueMember = ID;\n\n  var graphics = CreateGraphics();\n\n  // Set width of the drop down list based on the largest item in the list\n  CustomerColumn.DropDownWidth = (from width in\n                         (from DataRow item in _customersDataTable.Rows\n                          select Convert.ToInt32(graphics.MeasureString(item[Customer_Name].ToString(), Font).Width))\n                       select width).Max();	0
11738232	11738093	c# xml - show only one item/node if item names are the same	Dictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\nforeach (XmlNode items in diagramTables)\n{\n  string pkTable = items["PKTABLE_NAME"].InnerText.Replace("_",@"\_");\n  string fkTable = items["FKTABLE_NAME"].InnerText.Replace("_",@"\_");\n  if (!dict.ContainsKey(pkTable))\n  {\n    dict.Add(pkTable, new List<string>());\n  }\n  if (!dict[pkTable].Contains(fkTable))\n  {\n      dict[pkTable].Add(fkTable);\n  }\n}\nsb.Append("========================================================="); // making it easier for you\nforeach(KeyValuePair<string, List<string>> kvp in dict)\n{\n  sb.Append(kvp.Key);\n  sb.Append(" got ");\n  sb.AppendLine(String.Join("|", kvp.Value.ToArray()));\n}\nsb.Append("========================================================="); // making it easier for you	0
13434032	13433963	Concat multiple IEnumerables with constraint	var offers = ov.Offers.Where(o => o.OfferType == composedOffer)\n    .Concat(ov.Offers.Where(o => o.OfferType == simpleOffer))\n    .Concat(ov.ComposedOfferList.Offers)\n    .Concat(ov.SimpleOfferList.Offers)\n    .GroupBy(offer => offer.Product)\n    .Select(group => group.First())\n    .ToList();\n\nvar products = offers.Select(offer => offer.Product).ToList();	0
26878289	26878264	ASP.NET MVC ActionResult How to return data in response to GET request	[HttpGet]\n    public ActionResult GetOldEntries()\n    {\n        var data = db.Entries.Where(e => e.Date.Month != DateTime.Now.Month);\n        return Json(data, JsonRequestBehavior.AllowGet); \n    }	0
13512244	13511475	How would one use lynx.exe on windows to convert html string (with css & malformed html) to plain text	using System;\nusing System.Diagnostics;\n\nnamespace Lynx.Dumper\n{\n  public class Dampler\n  {\n      public void fdksfjh()\n      {\n          var url = "http://www.google.com";\n\n          var p = new Process();\n\n          p.StartInfo = new ProcessStartInfo("c:/tools/lynx_w32/lynx.exe", "-dump -nolist " + url)\n          {\n              WorkingDirectory = "c:/tools/lynx_w32/",\n              UseShellExecute = false,\n              RedirectStandardOutput = true,\n              RedirectStandardError = true,\n              WindowStyle = ProcessWindowStyle.Hidden,\n              CreateNoWindow = true\n          };\n\n          p.Start();\n          p.WaitForExit();\n\n          //grab the text rendered by Lynx\n          var text = p.StandardOutput.ReadToEnd();\n\n          Console.WriteLine(text);\n      }\n  }\n}	0
19159913	18698229	C# compare 2 files contents for matches	var fileAcontents = File.ReadAllLines(fileA);\nvar fileBcontents = File.ReadAllLines(fileB);\n\nHashSet<string> hashSet = new HashSet<string>(fileAcontents);\nforeach (string i in fileBList)\n{\n    if (hashSet.Contains(i))\n    {\n        // <- DO SOMETHING :)\n    }\n}	0
3757947	3757916	How to give dynamic DataSource name in App.config	ConfigurationManager.ConnectionStrings["Excels"].ConnectionString.Replace("[Today'sDate]", DateTime.Today.ToString("fmt"))	0
3091429	3091362	Cast from IEnumerable to Queryable in select statement?	public class FakeUserRepository : IUserRepository {\n          public IQueryable<SelectListItem> GetRecords(int userid) {\n                    // fake_table is a list\n                    return (from a in fake_table select\n                    new SelectListItem {\n                        Value = a.ID.ToString(),\n                        Text = a.Name\n                    }).AsQueryable<SelectListItem>;\n          }\n    }	0
27892388	27890265	DevExpress Gridview - different datasource on column in display mode	protected void ASPxGridView2_CustomColumnDisplayText(object sender,\n    DevExpress.Web.ASPxGridViewColumnDisplayTextEventArgs e) {\n    if (e.Column.FieldName != "FormatType") return;\n    e.DisplayText = WebApp.Helpers.CodebooksHelper.GetItemData(1).First(item => item.ItemID == (int)e.Value).Title;\n}\n\nsettings.CustomColumnDisplayText += (sender, e) => {\n        if (e.Column.FieldName != "FormatType") return;\n        e.DisplayText = WebApp.Helpers.CodebooksHelper.GetItemData(1).First(item => item.ItemID == (int)e.Value).Title;\n}	0
26436346	26436073	How to display my list<T> elements in a text box	class ListBoxItem\n{\n    public string Name { get; private set; }\n    public string Email { get; private set: }\n\n    public ListBoxItem(string name, string email)\n    {\n        Name = name;\n        Email = email;\n    }\n\n    public override string ToString()\n    {\n        return string.Format("Name: {0} | E-mail: {1}", Name, Email);\n    }\n}\n\n(somewhere you have a List<ListBoxItem> and do something like listBox1.Items.AddRange(itemList))\n\nprivate void listBox1_DoubleClick(object sender, EventArgs e)\n{\n    ListBoxItem item = (ListBoxItem)listBox1.SelectedItem;\n\n    // use item.Name and item.Email to initialize TextBox values\n}	0
13348270	13348022	Establish if a NetworkStream has finished reading	XDocument.Parse	0
6945715	6945587	How can I format the value when adding it to a DataGridView column?	String value = MBRHISTDETLDt.Rows[r].ItemArray[0].ToString(); \nvalue  = Regex.Replace(value.TrimStart('0'), @"^(\d{3})(\d{2})(\d{3})(\d*)$", "$1-$2-$3.$4");\ndataGridView1.Rows[r].Cells[2].Value = value;	0
1411609	1411577	Ignoring a field during .NET JSON serialization; similar to [XmlIgnore]?	public class Item\n{\n[ScriptIgnore]\npublic Item ParentItem { get; set; }\n}	0
20513625	20513382	Displaying a message box after a certain period of time	static System.Windows.Threading.DispatcherTimer myTimer = new System.Windows.Threading.DispatcherTimer();\n\npublic void DoInquiry()\n{\n   // do your inquiry stuff\n   ////////////////////////\n\n   // Set Timer Interval\n   myTimer.Interval = = new TimeSpan(0,5,0); // 5 Minutes\n   // Set Timer Event\n   myTimer.Tick += new EventHandler(TimerEventProcessor);\n\n   // Start timer\n   myTimer.Start();\n\n}\n\nprivate static void TimerEventProcessor(Object myObject, EventArgs myEventArgs) {\n   ShowMessage("Please check on the status");  \n}\n\nprotected void ShowMessage(string Message)\n{\n   System.Windows.MessageBox.Show(Message);\n}	0
1250077	1250071	C# standards/style for a Delphi developer?	public class Person {\n  private String _personName;\n  public String PersonName { \n    get { return _personName; }\n    set { _personName = value; }\n  }\n\n  public String SayHello(String toName ) {\n    return String.Format("Hi {0}, I am {1}", toName, PersonName);\n  }\n\n}	0
3175635	3175567	How do I prevent a popup form from taking focus from the parent	protected override bool ShowWithoutActivation {\n        get { return true; }\n    }	0
27749362	27697650	Accessing Source Depot Changelists from C#	Process process = new Process();\nprocess.StartInfo.UseShellExecute = false;\nprocess.StartInfo.RedirectStandardOutput = true;\nprocess.StartInfo.FileName = "sd.exe";\nprocess.StartInfo.Arguments = string.Format("describe {0}", newChangelist);\nprocess.Start();\n\n// read strings from process.StandardOutput here\n\nprocess.WaitForExit();	0
3782785	3767217	Selenium 2 WebDriver - Chrome - Getting the value from a text box that is set via JavaScript	public string TextInABox(By by)\n  {\n    string valueInBox = string.Empty;\n    for (int second = 0;; second++) {\n      if (second >= 60) Assert.Fail("timeout");\n      try\n      {\n        valueInBox = driver.FindElement(by).value;\n        if (string.IsNullOrEmpty(valueInBox) break;\n      }\n      catch (WebDriverException)\n      {}\n      Thread.Sleep(1000);\n    }\n    return valueInBox;\n  }	0
18079060	18016260	How to set a dependancy property from a style trigger	public override void OnApplyTemplate()\n        {\n            base.OnApplyTemplate();\n            _elementName = Template.FindName("PART_ElementName", this) as TextBlock;\n            _elementText = Template.FindName("PART_ElementText", this) as TextBlock;\n\n            if (_elementName != null) _elementName.MouseLeftButtonDown += (sender, args) => SelectControl();\n            if (_elementText != null) _elementText.MouseLeftButtonDown += (sender, args) => SelectControl();\n        }	0
7525441	7525395	C# - Inheritance, override	abstract class A { \n public virtual string Print() {} \n\n  public static string DoPrint(A a) { \n     a.Print(); // <-- This WILL call eg. A3.Print(), not A.Print() \n  } \n} \n\nclass A1 : A\n{\n    public override string Print() {}\n}\n\nclass A2 : A\n{\n    public override string Print() {}\n}\nclass A3 : A\n{\n    public override string Print() {}\n}	0
7068619	7068043	How to get the default value for a ValueType Type with reflection	public static object GetDefault(this Type t)\n{\n    return t.IsValueType ? Activator.CreateInstance(t) : null;\n}\n\npublic static T GetDefault<T>()\n{\n    var t = typeof(T);\n    return (T) GetDefault(t);\n}\n\npublic static bool IsDefault<T>(T other)\n{\n    T defaultValue = GetDefault<T>();\n    if (other == null) return defaultValue == null;\n    return other.Equals(defaultValue);\n}	0
11051987	11051508	How to read a csv or text file using c# and count characters line by line of that file and show if less than 1500?	string[] lines = File.ReadAllLines("filename.txt");\n        int count = 0;\n        int line = 0;\n\n        for (; line < lines.Length; line++)\n        {\n            count += lines[line].Length;\n            if (count >= 1500)\n            {\n                // previous line is < 1500\n                Console.WriteLine("Character count < 1500 on line {0}", line - 1);\n                Console.WriteLine("Line {0}: {1}", line - 1, lines[line - 1]);\n                break;\n            }\n        }	0
31548389	31548161	C# Dllimport - pointer to a pointer receiving array	[DllImport("remoteApi.dll", CallingConvention = CallingConvention.Cdecl)]\npublic static extern int simxGetObjects(\n    int clientID, \n    int objectType, \n    out int objectCount, \n    out IntPtr objectHandles, \n    int operationMode\n);\n\nint objectCount;\nIntPtr objectHandles;\n\nint result = simxGetObjects( clientID, \n                             objectType, \n                         out objectCount, \n                         out objectHandles, \n                             operationMode );\nif( result == 0 && objectHandles != IntPtr.Zero )\n{\n    for( int index = 0; index < objectCount; index++ )\n    {\n        IntPtr handle = (IntPtr)((int)objectHandles + index*4);\n\n        // do something with handle            \n    }\n}	0
8182935	8182895	How to serialize / deserialize a double value independent of culture	double d = 2.0;\n\nvar invariantString = Convert.ToString(d, CultureInfo.InvariantCulture);\n\nvar d2 = Convert.ToDouble(invariantString, CultureInfo.InvariantCulture);	0
11085650	11085445	SelectionChangedEventHandler for a TabControl in WPF	var tabControl = e.Source as TabControl;\nvar oldTabItem = e.RemovedItems[0] as TabItem;\nvar oldIndex = tabControl.Items.IndexOf(oldTabItem);	0
13808107	13807154	How to convert a decimal to any currency in WinRT?	CultureInfo.CreateSpecificCulture("nl-NL");	0
30590072	30589890	Set var in foreach to use later	var sReg;\n@foreach (var userid in db.Query(selectUser)) \n{\n    sReg = userid.userdisplayname;\n    var sAns = userid.usersign;\n    var smail = userid.usermail;\n}	0
7242843	7211142	How to get screenshot from clipboard?	// get the bounding area of the screen containing (0,0)\n// remember in a multidisplay environment you don't know which display holds this point\nDrawing.Rectangle bounds = Forms.Screen.GetBounds(System.Drawing.Point.Empty);\n\n// create the bitmap to copy the screen shot to\nDrawing.Bitmap bitmap = new Drawing.Bitmap(bounds.Width, bounds.Height);\n\n// now copy the screen image to the graphics device from the bitmap\nusing (Drawing.Graphics gr = Drawing.Graphics.FromImage(bitmap))\n{\n    gr.CopyFromScreen(Drawing.Point.Empty, Drawing.Point.Empty, bounds.Size);\n}	0
21287228	21286842	Problems adding JS OnClientClick to a button in code-behind	btnLink.OnClientClick =\n    "window.parent.openlink('http://www.google.co.uk', 'test', 300, 300);return false;";	0
7620622	7570652	how to keep the text of a Read only textbox after post-back?	protected void Page_Load(object sender, EventArgs e)\n{\n     TextBox1.Attributes.Add("readonly", "readonly");\n}	0
27429312	27429082	String pattern matching in c#	public string GenerateNumber(string input)\n{\n    if (string.IsNullOrWhiteSpace(input))\n    {\n        throw new ArgumentNullException("input");\n    }\n\n    Random rand = new Random();\n    StringBuilder builder = new StringBuilder();\n\n    for (int i = 0; i < input.Length; i++)\n    {\n        if (input[i] == '-')\n        {\n            builder.Append("-");\n        }\n        else\n        {\n            builder.Append(rand.Next(0, 9).ToString());\n        }\n    }\n\n    return builder.ToString();\n}	0
7715248	7715206	read a pdf file from url to to byte array	WebClient.DownloadData()	0
20843516	20769226	how to get an item with a link	// creates a Podio.API.Client used to communicate with the Podio API\nvar client = Podio.API.Client.ConnectAsUser(client_id, client_secret, username, password);\n\nint AppId = 9999;\nstring requestUrl = Podio.API.Constants.PODIOAPI_BASEURL + "/tag/app/" + AppId + "/";\n\n// request the api\nPodio.API.Utils.PodioRestHelper.PodioResponse response = Podio.API.Utils.PodioRestHelper.Request(requestUrl, client.AuthInfo.access_token);	0
22541904	22541818	XML Serialization: Object attribute maps to 2 xml elements	[XmlElement("password")]\npublic string Password { get; set; }\n\n[XmlElement("password_confirmation")]\npublic string PasswordConfirmation{ get { return Password;} set; }	0
6132121	6129788	c# can you get position from axis without having a form?	Bitmap canvas = new Bitmap(600, 480);\nGraphics graph = Graphics.FromImage(canvas);	0
11400986	11400516	I need to be able to depopulate a listbox	private void lbz_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    if( lbz.SelectedItem != null ){\n        if(File.Exist(lbz.SelectedItem.ToString())){\n            tb1.Text = File.ReadAllText(lbz.SelectedItem.ToString());\n        }\n        else\n        {\n            tb1.Text = "File is not exist in the selected Path";\n        }\n    } else {\n        tb1.Text = "No File Selected";\n    }\n}	0
29339547	29339419	How to hide a row based on condition in gridview	GridImport.DataSource = dtTemSec.AsEnumerable()\n                                .Where(x => x.Field<string>("Status") != "D")\n                                .CopyToDataTable();\nGridImport.DataBind();	0
10449665	10449635	Use of unassigned local variable - if statements	string strType = null;	0
10050221	10050160	Packaging a .NET Application So It Will Run On A Computer Without .NET	dotnetfx35.exe /q /norestart	0
6543053	6542919	Parameterize database column names in controller action	public ActionResult ProfessorStatus(string schoolType) {\n  Expresison<Func<Professor, bool>> filter;\n  switch (schoolType) {\n    case "Engineering":\n      filter= a => a.Engineering.Value == true;\n      break;\n    default:\n      throw new Exception("Unknown SchoolType - " + schoolType);\n  }\n  var activeProfessors = (from p in prof.ProfessorTable.Where(filter)\n     group p by p.ProfessorID into g\n     select g.Key).ToList();\n  return View(activeProfessors);\n}	0
2181630	2181613	string.format conundrum	{1} _{0};\ninternal {1} {0}\n{{\n    get {{ return _{0}; }}\n    set\n    {{\n        _{0} = value;\n        UpdateRowValue(myObj, "{0}", value);\n    }}\n\n}}\ninternal void SetNull{0}()\n{{\n    UpdateRowValue(myObj, "{0}", DBNull.Value);\n}}	0
4527051	4527023	get text of the clicked node treeview C# winforms	private void treeView1_NodeMouseClick(object sender, TreeNodeMouseClickEventArgs e) {\n        Console.WriteLine(e.Node.Text);\n    }	0
16333468	16331770	json parsing issues with escape characters in json.net	contentCorrected = contentCorrected.Replace(@"\", "");	0
15675470	15659491	How to install clrzmq using Package Manager Console for a console c# application?	using ZMQ;\n\nnamespace TestConsole \n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            // ZMQ Context and client socket\n            using (Context context = new Context())\n            using (Socket client = context.Socket(SocketType.PUSH))\n            {\n                client.Connect("tcp://127.0.0.1:2202");\n\n                string request = "Hello";\n                for (int requestNum = 0; requestNum < 10; requestNum++)\n                {\n                    Console.WriteLine("Sending request {0}...", requestNum);\n                    client.Send(request, Encoding.Unicode);\n\n                    string reply = client.Recv(Encoding.Unicode);\n                    Console.WriteLine("Received reply {0}: {1}", requestNum, reply);\n                }\n            }\n        }\n    }\n}	0
17601452	17593496	how can i use generic to PdfPcells	public static PdfPCell MakeHeader(string text, iTextSharp.text.Font Htitle) {\n    PdfPCell HeadCell = new PdfPCell(new Paragraph(text, Htitle));\n    HeadCell.BackgroundColor = iTextSharp.text.Color.LIGHT_GRAY;\n\n    return HeadCell;\n}\n\nPdfPCell HeadCell0 = MakeHeader("FullName", Htitle);	0
14779788	14779702	Data Mapping an Adjacency List Model with AutoMapper	public static void ConfigureMappings()\n{\n  Mapper.CreateMap<TreeNodeDto, Taxonomy>()\n  .AfterMap((s, d) =>\n  {  \n     //WCF service calls to get parent and children\n     d.Children =  Mapper.Map<TreeNodeDto[], TreeNode[]>(client.GetTreeChildren(s)).ToList();\n    foreach( var child in d.Children)\n    {\n       child.Parent = d;\n    }\n}	0
24010544	24009770	XML writer with custom formatting	var sb = new StringBuilder();\n  var settings = new XmlWriterSettings {\n    OmitXmlDeclaration = true,\n    Indent = true,\n    IndentChars = "  ",\n  };\n  using (var writer = XmlWriter.Create(sb, settings)) {\n    writer.WriteStartElement("X");\n    writer.WriteAttributeString("A", "1");\n    writer.Flush();\n    sb.Append("\r\n");\n    writer.WriteAttributeString("B", "2");\n    writer.Flush();\n    sb.Append("\r\n");\n    writer.WriteAttributeString("C", "3");\n    writer.WriteEndElement();\n  }\n  Console.WriteLine(sb.ToString());	0
7216711	7215056	using List with values come from SQL	List<Bar> bar = new List<Bar>() \n    { \n        new Bar() { Id = 1, Name = "John Smith" }, \n        new Bar() { Id = 2, Name = "Jane Doe" }, \n        new Bar() { Id = 3, Name = "Joe Johnson" } \n    };\n\n//query the bar list and select the name \nstring name = bar.Where(x => x.Id == 2).Select(x => x.Name).FirstOrDefault();	0
18009355	18009000	Value height image on mouseover bigger than image height	Int32 h = picture.Height;\nInt32 w = picture.Width;\nif (e.X < w && e.Y < h)\n{\n    Int32 R = picture.GetPixel(e.X, e.Y).R;\n    Int32 G = picture.GetPixel(e.X, e.Y).G;\n    Int32 B = picture.GetPixel(e.X, e.Y).B;\n    lbPixelValue.Text = "R:" + R + " G:" + G + " B:" + B;\n    lbCoordinates.Text = String.Format("X: {0}; Y: {1}", e.X, e.Y);\n}\nelse\n{\n    lbPixelValue.Text = "";\n    lbCoordinates.Text = "";\n}	0
26618016	26617966	Function to display single returned value from SQL Server stored procedure	using(SqlConnection cnn = new SqlConnection(....here the connection string ....))\nusing(SqlCommand cmd = new SqlCommand("uspRetMostCommonScreenRes", cnn))\n{\n    cnn.Open();\n    cmd.CommandType = CommandType.StoredProcedure;\n    string result = cmd.ExecuteScalar().ToString();\n}	0
26013174	26012315	How to redirect other page after successfully login by a class on WCF	Login UserLogin = new Login();\n   UserLogin.Username = textBox1.Text;\n   UserLogin.Password = textBox2.Text;\n   if(objServiceClientobjService.UserLogin(UserLogin))\n         {\n               Response.Redirect("Home.html"); // your page to go after valid user login\n         }\n     else\n         {\n             // show error code\n         }	0
28085400	28085284	Attach text file to mail using C# for Windows-mobile	EmailMessage message = new EmailMessage();\n Recipient myrecipient = new Recipient("Gmail", "MyMail@gmail.com");\n message.To.Add(myrecipient);\n //Adding more To address\n message.To.Add(myrecipient2);\n message.To.Add(myrecipient3);\n //Adding more CC address\n message.Cc.Add(myrecipient4);\n message.Cc.Add(myrecipient5);\n //Adding more Bcc address\n message.Bcc.Add(myrecipient6);\n message.Bcc.Add(myrecipient7);\n message.Subject = "test from Windows-Mobile";                          \n message.BodyText = "this is the test from Windows-Mobile";        \n //Adding attachments\n message.Attachments.Add("TextFilePath");\n message.Send("Gmail");                                                \n MessagingApplication.Synchronize("Gmail");                     \n SetForegroundWindow(this.Handle);	0
2408084	2407986	Get all sub directories from a given path	static IEnumerable<string> GetSubdirectoriesContainingOnlyFiles(string path)\n{\n  return from subdirectory in Directory.GetDirectories(path, "*", SearchOption.AllDirectories)\n         where Directory.GetDirectories(subdirectory).Length == 0\n        select subdirectory;\n}	0
24659016	24640634	Winform running on Parallels with SQLite	SQLiteConnection dbConnection = new SQLiteConnection("Data Source=mydb.db3;Version=3;", true);	0
21581315	21581160	Add column to ASP.net Gridview using C#	BoundField boundfield = new BoundField();\nboundfield.DataField = "Last Name";\nboundfield.HeaderText = "Last Name";\nboundfield.SortExpression= "LastName";\nGridView1.Columns.Add(boundfield);	0
12416466	12416441	How can i check for duplicate items in a List<string>?	var distinctOnes = a.Distinct();	0
29740752	29740042	set Check to treeView checkbox	private void chechTreeViewItems(List<int> remID)\n{\n    foreach (System.Windows.Forms.TreeNode item in this.tvRemark.Nodes[0].Nodes)\n    {\n        for (int i = 0; i < remID.Count; i++)\n        {\n            if (Convert.ToInt16(item.Tag) == remID[i])\n            {\n                item.Checked = true;\n            }\n        }\n    }\n}	0
10272143	10272051	c# - Want to perform an action if a user enters a node that already exists in a xml file	if (doc.SelectSingleNode("/Schedule/Date[text()='" + monthCalander1.SelectionStart.ToString() + "']") != null){\n   // already exists, do something here\n}	0
26289477	26283603	Default value for DateTime in DevForce 2012	ServiceRequest.PropertyMetada.CreatedDate.DefaultValue	0
11618660	11617781	SelectorRegionAdapter and TabControl: How to correctly use it?	TabControl.ItemContainerStyle	0
18333092	18333067	Session variables set - Page_Load method C#	Session["confirmBooking"] = "confirm";\nSession["totalBooking"] = calculateTextBox.Text;\nResponse.Redirect("RoomBookingMain.aspx");	0
22680252	22680170	How to determine whether the app is returning from being dormant or tombstone?	private void Application_Activated(object sender, ActivatedEventArgs e)\n{\n     // Determine whether it is returning from being dormant or tombstoned.\n     // If it is false, return from tombstoned.\n     if (e.IsApplicationInstancePreserved == false)\n         //TODO\n     else\n         //TODO\n }	0
11556682	11556473	Finding latest record in a List	var negList = rms.NegativeResponse.Where(d => d.RLMSTimeStamp != null && d.RLMSTimeStamp > new DateTime(2012, 02, 22)).toList();\nvar posList = rms.PositiveResponse.Where(d => d.RLMSTimeStamp != null && d.RLMSTimeStamp > new DateTime(2012, 02, 22)).toList();\n\n\nvar item = (from pos in posList\n            join neg in negList\n              on\n                 pos.RLMSRecruitId equals neg.RLMSRecruitId\n              orderby pos.RLMSTimestamp descending\n              select pos).FirstOrDefault();	0
28836506	28836420	How do I add ONLY specific DB Entity Sets to the ViewData in ASP.NET MVC 4 Entity Framework?	ViewData.Model = _selectedJobDb.Jobs.Where(j => j.Request.TargetName == TargetName).ToList();	0
18861979	18861174	C# mind bender: Compile string to assignment expression at runtime	System.CodeDom	0
18615663	18503783	Accessing a header or footer creates it, but leaving an empty one doesn't	activeWindow.ActivePane.View.Type = WdViewType.wdPrintView;\nactiveWindow.ActivePane.View.SeekView = WdSeekView.wdSeekPrimaryHeader;\n\n//Check for blank headers\nactiveWindow.ActivePane.Selection.WholeStory();\nvar text = activeWindow.ActivePane.Selection.Text;\nif (!string.IsNullOrEmpty(text) && text.Equals("\r"))\n{\n    activeWindow.ActivePane.View.SeekView = WdSeekView.wdSeekMainDocument;\n    continue;\n}\n// Get the full range of the header. This call causes my problem.\nRange headerRange = header.Range;	0
11395362	11395315	Get value of a specific object property in C# without knowing the class behind	System.Reflection.PropertyInfo pi = item.GetType().GetProperty("name");\nString name = (String)(pi.GetValue(item, null));	0
10087762	9823538	Please help me fix this crash on Windows XP and any version of IE	var field = browser.TextField(Find.ByName("_MYPW"));\nif(field.Exists)\n    field.TypeText(privateCurrentPassword);	0
26212145	26210603	WCF Rest service first send response then save file in local folder	Thread t = new Thread(() => saveFile(args));\nt.Start();	0
23098649	23098517	How can I open a file in my WPF app, when the user double-clicks on that file?	Environment.GetCommandLineArgs	0
9490704	9474000	HttpWebResponse stripping newline characters	using (StreamReader MyResponseStream = new StreamReader(hwresponse.GetResponseStream()))\n{\n    using (StreamWriter _FileStream = new StreamWriter("request.txt", true))\n    {\n        _FileStream.Write(MyResponseStream.ReadToEnd());\n    }\n}	0
32385111	32384489	how to upload multiple files to a folder and then display that files in datagridview in c# windows application	public string Path { get; set; }\nprivate void UploadButton_Click(object sender, EventArgs e)\n{\n    var o = new OpenFileDialog();\n    o.Multiselect = true;\n    if(o.ShowDialog()== System.Windows.Forms.DialogResult.OK)\n    {\n        o.FileNames.ToList().ForEach(file=>{\n            System.IO.File.Copy(file, System.IO.Path.Combine(this.Path, System.IO.Path.GetFileName(file)));\n        });\n    }\n\n    this.LoadFiles();\n}\n\nprivate void Form_Load(object sender, EventArgs e)\n{\n    this.LoadFiles();\n}\n\nprivate void LoadFiles()\n{\n    this.Path = @"d:\Test";\n    var files = System.IO.Directory.GetFiles(this.Path);\n    this.dataGridView1.DataSource = files.Select(file => new { Name = System.IO.Path.GetFileName(file), Path = file }).ToList();\n}	0
10887672	10887493	Stored Procedure with output parameters connected to method in C#	.ToString()	0
25803139	25802837	how to use action filter when i have 2 method with same name with different protocol	if (actionDescriptor.ControllerDescriptor.ControllerType == typeof(HomeController) &&\n                  (actionDescriptor.ActionName.Equals("home")) && controllerContext.HttpContext.Request.HttpMethod == "POST" )	0
21480941	21475014	I want zip file without any directories in zip file.How can I do in c#	string filepath = @"C:\Users\H?seyin\Desktop\AA\a.txt";\n        zip.AddItem(filePath, Path.GetFileName(filePath));	0
3004261	3004204	How do I select the item with the highest value using LINQ?	Foo max = list.MaxBy(f => f.value);	0
31350960	31350732	WPF data grid changing data in all columns	IsSynchronizedWithCurrentItem="True"	0
8639380	8631139	Avoid the magic string when injecting a constructor argument from an attribute using Ninject's BindFilter method?	this.BindFilter(\n    x => new PermitFilter(\n        x.Inject<ISomeDependency>(),\n        x.FromControllerAttribute<PermitAttribute>().GetValue(attribute => attribute.Permissions)), \n        FilterScope.Controller, \n        0)\n    .WhenActionMethodHas<PermitAttribute>();	0
18815761	18815570	How to Sort a LongListSelector in Windows Phone	App.PictureList.Pictures.OrderBy(x => x.DateTaken) as System.Collections.IList	0
21102357	21100992	Using MVC5's RoutePrefix with areas	AccountAreaRegistration.cs	0
3314768	3314711	How do I implement an abstract event or interface method event in C#?	interface IFoo\n{\n    event EventHandler OnChanged;\n}\n\nclass MyClass : IFoo\n{\n    public event EventHandler OnChanged;\n\n    private FireOnChanged()\n    {\n        EventHandler handler = this.OnChanged;\n        if (handler != null)\n        {\n            handler(this, EventArgs.Empty); // with appropriate args, of course...\n        }\n    }\n}	0
27016141	27015805	Remove all commas from a string in C# 3	a = a.Replace("," , "");	0
28946080	28945881	Date condtion doesn't work on my application but work in SQL Server	SqlCommand command = new SqlCommand("Select * from whatever where Date Between @begin and @end");\n command.Parameters.Add(new SqlParameter("begin", yourbegin));\n command.Parameters.Add(new SqlParameter("end", yourEnd));\n ...	0
17734883	17734791	Aligning html inputs on same line 2	display:inline-block	0
12374026	12373899	ASP.NET C# Entity Framework - How to update Foreign Key properly?	var Data = base.Entities.Member.First(c => c.Id == entity.Id);\nif (Data != null)\n{\n    Data = entity;\n    base.Entities.SaveChanges();\n}	0
5519566	5519462	Starting WinForm From Clicking Gallery Item[DevExpress]	private void PictureClicked(object sender, EventArgs e) {\n    Control picture = sender as Control;\n    if (picture == null) //just in case...\n        return;\n    switch (picture.Name) {\n        case "pictureBoxCar":\n            //open Car form\n            break;\n        case "pictureBoxBoat":\n            //open Boat form\n            break;\n    }\n}	0
8722118	8720702	Xpath node selection - how to select 2 different elements - htmlagilitypack	string srxPathOfCategory = "//div[@class='breadcrumbs']//li[@class='product'] | //div[@class='breadcrumbs']//a";	0
10240945	10240859	How convert IQueryable<IQueryable<Page>> to IQueryable<Page> with Linq	var articlePages = categoryPages.SelectMany(x => x.ChildPages);	0
3273367	3234487	Update parent table from child in Asp.net and fluent nhibernate	UpdateModel(child.parent, "Parent", new[] { "child.parent.parentValue1", "child.parent.parentValue2", "child.parent.parentValue3" }, collection.ToValueProvider());	0
11772352	11734862	WCF - communication between two methods	public class TestClass \n{\n    public static event OrderUpdateHandler UpdatedOrder;\n\n    public void UpdateData(Order order) \n    {\n        // ...\n\n        OnOrderUpdated(args);\n    }\n\n    public Order GetConfirmedOrder(int id, TimeSpan waitToConfirm) \n    {\n        var order = GetOrderFromDatabase();\n\n        if (order.Status == OrderStatus.Pending) \n        {\n             var eventHandle = new EventWaitHandle(false, EventResetMode.AutoReset);\n\n             UpdatedOrderHandler waiter = (s, e) =>\n             {\n                if (e.Order.Id == id)\n                {\n                    order = e.Order;\n                    eventHandle.Set();\n                }\n            };\n\n            UpdatedOrder += waiter;\n\n            if (!eventHandle.WaitOne(waitToConfirm))\n            {                \n                return order;\n            }\n\n            OrderUpdated -= waiter;\n        }\n\n        return order;\n    }\n}	0
31677835	31677347	Find the name of a repeater control on form load	Request.Form["__EVENTTARGET"]	0
9927977	9927779	How to convert Dictionary<> to Hashtable in C#?	var dictionary = new Dictionary<object, object>();\n        //... fill the dictionary\n        var hashtable = new Hashtable(dictionary);	0
6787498	6787456	If I add a try-catch block with just Debugger.Break() in catch	private void DoSomething()\n{\n#if DEBUG\n    try\n    {\n#endif\n        //do something\n#if DEBUG\n    }\n    catch\n    {\n        Debugger.Break();\n        throw;\n    }\n#endif\n}	0
302023	301965	Best way to periodically remove a set of records with LINQ to SQL	DELETE * FROM tblSignIns \n WHERE LastActivityTime < DATEADD("minute", -10, GETDATE());	0
33621775	33621626	how to read the file via Windows Explorer which is be holding by StreamWriter?	var fileStream = File.Open(file, FileMode.Append, FileAccess.Write, FileShare.Read);\nvar streamWriter = new StreamWriter(fileStream);\nstreamWriter.AutoFlush = true;	0
17041926	17041880	How to get Dataset table column data type in C#	if (Dataset1.Tables[0].Columns[1].ColumnName.ToLower().Contains("date") || Dataset1.Tables[0].Columns[1].DataType.ToString() == "System.DateTime")                              \n{\n   //Do work;\n}	0
24680452	24665520	Detect an empty [{}] json object in manged code	//an empty file ( [{}] will return positive for HasElements so we also get \nbool IsEmptyObject = (root.Elements().Nodes().Count() > 0) ? true : false;	0
29006795	29006136	How to generate from one point a set of circle points?	class Program\n{\n    static void Main(string[] args)\n    {\n        int n = 22; //the number of points\n        float radius = 22f;\n        Vector3 vector = new Vector3(radius, 0, 0); //the vector you keep rotating\n        Vector3 center = new Vector3(33,33,33); //center of the circle\n        float angle = (float)Math.PI * 2 / (float)n;\n\n        Vector3[] points = new Vector3[n];\n\n        Matrix rotation = Matrix.RotationZ(angle);\n\n        for (int i = 0; i < n; i++)\n        {\n            points[i] = vector + center;\n\n            vector.TransformNormal(rotation);\n        }\n    }\n}	0
1831845	1831801	Retrieving images using a file path stored in a sql database	var connectionString = ConfigurationManager.ConnectionStrings["SomeCN"].ConnectionString;\nusing (var cn = new SqlConnection(connectionString))\nusing (var cmd = cn.CreateCommand())\n{\n    cn.Open();\n    cmd.CommandText = "select imageid from accounts where accountid = @accountid";\n    cmd.Parameters.AddWithValue("@accountid", 5);\n    using (var reader = cmd.ExecuteReader())\n    {\n        if (reader.Read())\n        {\n            var filePath = reader.GetString(0);\n            // For this to work images must be stored inside the web application.\n            // filePath must be a relative location inside the virtual directory\n            // hosting the application. Depending on your environment some\n            // transformations might be necessary on filePath before assigning it\n            // to the image url.\n            imageControl.ImageUrl = filePath;\n        }\n    }\n}	0
29869758	29869599	How to add elements to a C# list from MATLAB?	list = NET.createGeneric('System.Collections.Generic.List',...\n  {'System.Int32'},100);\nlist.Add(5)\nlist.Add(6)\n\nfor i = 0:list.Count - 1\n   disp(list.Item(i))\nend	0
10490884	10490801	LINQ to XML - Group by parent element	XDocument MyXDoc;\n// TODO, load or parse MyXDoc\n\nstring[] CsvList = MyXDoc.Root.Elements("row")\n    .Select(row => \n        String.Join(", ", row.Elements("value").Select(val => (string)val).ToArray() )\n     )\n    .ToArray();	0
22038901	22038381	Parsing the XML and add it as Key Value pair	var xmlDict = XDocument.Load(filename).Root.Element("dict");\nvar dict = xmlDict.Elements("key")\n           .Zip(xmlDict.Elements("string"), (k, s) => new KeyValuePair<string, string>(k.Value, s.Value))\n           .ToDictionary(x=>x.Key,x=>x.Value);	0
16823732	16823518	Calling Batch File From C#	System.Diagnostics.Process proc = new System.Diagnostics.Process();\nproc.StartInfo.FileName = "C:\\Watcher\\Cleanup.bat";\nproc.StartInfo.WorkingDirectory = "C:\\Watcher";\nproc.Start();	0
2990662	2990647	Multiple objects in list, C#	List<Tuple<T1, T2, ...>>	0
2677445	2677169	How to develop applications in C# that can be further extended using DLL add-ins? Like .NET Reflector	System.Activator.CreateInstance\nSystem.Reflection.Assembly.LoadFrom	0
15279899	15279861	I want to copy a file to another server, but I'm getting a "could not find part of path" error	file.CopyTo(@"\\123.45.678\etcetc");	0
16122311	16122276	Search text file for user variable - Whats wrong with this code	line = myReader.ReadLine();                                                     \nif (line != null && line.IndexOf(x, StringComparison.CurrentCultureIgnoreCase) >= 0)\n      Console.WriteLine(line);	0
25165709	25159119	C# conversion issue from a generic value to string	Object obj = -0.00002357467;\n        String value = obj.ToString();\n        String type = obj.GetType().ToString();\n\n        if (type.Equals("System.Double")&&value.Contains("E-"))\n        {\n            double doubleValue = (double)obj;\n            value = doubleValue.ToString("0.############################"); //thanks @Matthew Watson\n        }\n\n        Console.WriteLine(value);   //prints -0.00002357467	0
29683069	29682614	Remove extra _ from mask	private void MaskedTextBox1_TextChanged(object sender, EventArgs e)\n{\n    MaskedTextBox1.PromptChar = (MaskedTextBox1.MaskCompleted) ? ' ' : '_' ;\n}	0
26281842	26257544	Parallel processing for a List	private void SetUpThreadPool(int numThreadDesired)\n{\n    int currentWorkerThreads;\n    int currentCompletionPortThreads;\n    ThreadPool.GetMinThreads(out currentWorkerThreads, out currentCompletionPortThreads);\n    //System.Diagnostics.Debug.WriteLine(string.Format("ThreadPool.GetMinThreads: workerThreads = {0}, completionPortThreads = {1}", workerThreads, completionPortThreads));\n\n    const int MAXIMUM_VALUE_FOR_SET_MIN_THREAD_PARAM = 20;\n    int numMinThreadToSet = Math.Min(numThreadDesired, MAXIMUM_VALUE_FOR_SET_MIN_THREAD_PARAM);\n    if (currentWorkerThreads < numMinThreadToSet)\n        ThreadPool.SetMinThreads(numThreadDesired, currentCompletionPortThreads);\n}\n\npublic List<int> ProcessList(List<int> itemsToProcess)\n{\n    SetUpThreadPool(documentNumberList.Count);\n    ...\n}	0
4686315	4685961	Databinding issue with stopwatched elapsed	public class Employee : System.ComponentModel.INotifyPropertyChanged	0
20285830	20283839	Json get underlying array without retrieving its member	dynamic data = Newtonsoft.Json.Linq.JObject.Parse(content);\nvar value = data.credits.cast as Newtonsoft.Json.Linq.JArray; \nvar actors = value.Select(x => x.ToObject<Actor>());	0
2335816	2335738	C# WPF project, how to avoid InvalidOperationException?	if (!Dispatcher.CheckAccess()) \n        {\n            Dispatcher.BeginInvoke(DispatcherPriority.Normal,\n            (MyDelegate)delegate\n            {\n                // Get value\n            });\n        } \n        else \n        { \n            // Get value\n        }	0
20406623	20359412	VTK ActiViz to reset object to original view	private vtkCamera camera;    \ncamera.SetPosition(DoubleArrayToIntPtr(defaultCamPos));\ncamera.SetViewUp(DoubleArrayToIntPtr(defaultCamViewup));\ncamera.SetFocalPoint(DoubleArrayToIntPtr(defaultCamFocus));	0
22742653	22742614	create method number generator in c# by parameter	// declare random instance outside of the method \n// because we don't want duplicate numbers\nstatic Random rnd = new Random();\n\npublic static int GenerateRandomNumber()\n{\n    // declare variables to store range of number\n    int from, to;\n\n    // use while(true) and force user to enter valid numbers\n    while(true)\n    {\n        // we use TryParse in order to avoid FormatException and validate the input\n        bool a = int.TryParse(Console.ReadLine(), out from);\n        bool b = int.TryParse(Console.ReadLine(), out to);\n\n        // check values and ensure that 'to' is greater than 'from'\n        // otherwise we will get a ArgumentOutOfRangeException on rnd.Next\n\n        if(a && b && from < to) break; // if condition satisfies break the loop\n\n        // otherwise display a message and ask for input again\n        else Console.WriteLine("You have entered invalid numbers, please try again.");\n    }\n\n    // generate a random number and return it\n    return rnd.Next(from, to + 1);\n\n}	0
20238565	20238367	Add text to row 1 in excel export listview	ws.Cells[j, 1] = "Category";\n            ws.Cells[j, 2] = "Part Number";\n            ws.Cells[j, 3] = "TradePrice";\n            ...	0
3981419	3981329	Executing a method by parameter in C#	var delegates = new Dictionary<string, Func<MyClass, DataTable>>()\n                                {\n                                    {"somestr", x => x.Method1()}\n                                };\n\n            if (delegates.ContainsKey(key))\n                delegates[key](this);	0
1282870	1282829	Is there a better way to make console games than with Console.Clear()?	Console.SetCursorPosition(0, 0);	0
4977230	4955422	Disable Space key for WebBrowser	onkeypress='if(event.keyCode=13) return false;'	0
1357212	1357203	C# - How to allow multiple filetypes in an OpenFileDialog?	files|*.txt;*.text	0
3983755	3982624	Is it possible to update the TOC (TableOfContents) of a Word document generated with Syncfusion's DocIO lib?	Document wordDocument;\nMicrosoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application(); \nwordDocument = word.Documents.Open(saveFileDialog.FileName);\nwordDocument.TablesOfContents[1].Update();\nwordDocument.Save();\nword.Quit();	0
21576001	21574061	WebAPI OData $format to xml	request.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/atom+xml");	0
4516720	4516139	Fluent NHibernate: How do I map Many-to-Many Relationships with additional attributes on the relationship table?	public class UserMap : ClassMap<User>\n{\n    public UserMap()\n    {\n        Id(x => x.UserId).GeneratedBy.Identity();\n        Map(x => x.UserName).Length(DataConstants.UserNameLength).Unique().Not.Nullable();\n        Map(x => x.EmailAddress).Length(DataConstants.EmailAddressLength).Unique().Not.Nullable();\n        Map(x => x.DateJoined).Not.Nullable();\n        Map(x => x.Password).Length(DataConstants.PasswordHashLength).Not.Nullable();\n        HasManyToMany(x => x.UserRoles).Cascade.AllDeleteOrphan().AsBag().Table("UsersInRole");\n        HasManyToMany(x => x.SubscribedFeeds).Cascade.DeleteOrphan().AsBag().Table("Subscriptions");\n        HasManyToMany(x => x.OwnedFeeds).Cascade.All().AsBag().Table("FeedOwners");\n        HasMany(x => x.Reads).Cascade.AllDeleteOrphan().Fetch.Join().Inverse().KeyColumn("UserId");\n    }\n}	0
10874038	10872649	A ViewStartPage can be used only with with a page that derives from WebViewPage or another ViewStartPage	public abstract class MyViewStart : System.Web.Mvc.ViewStartPage {\n    public My.Helpers.ThemeHelper Themes { get; private set; }\n\n    public override void ExecutePageHierarchy()\n    {\n        this.Themes = new Helpers.ThemeHelper(this.ViewContext);\n        base.ExecutePageHierarchy();\n    }\n}	0
18354908	18354865	Invalid argument value of '1' is not valid for 'index'	for (int i = 0; i < listView1.Items.Count; i++)\n    {\n    if (listView1.Items[i].Selected)\n      {\n        string var1 = listView1.Items[i].ToString();  // <-------\n        string var2 = var1.Substring(31, 5); \n        ... // code for other actions\n        listView1.Items[i].Remove();\n        i--;\n      }\n    }	0
24699606	24684914	Get Entity Framework 6 use NOLOCK in its underneath SELECT statements	using (new TransactionScope(\n                    TransactionScopeOption.Required, \n                    new TransactionOptions \n                    { \n                         IsolationLevel = IsolationLevel.ReadUncommitted \n                    })) \n{\n        using (var db = new MyDbContext()) { \n            // query\n        }\n}	0
11291861	11285928	Detecting a modal dialog box of another process	IsWindowEnabled()	0
2560282	2560217	Find Control In Datalist	protected void dlCategory_ItemDataBound(object sender, DataListItemEventArgs e) \n{\n    Label Label1 = e.Item.FindControl("Label1") as Label;\n    if (LblCat != null)\n    {\n        string id = ((System.Data.DataRowView)e.Item.DataItem).Row["ProductCategory_Id"].ToString();\n\n        if (Request.QueryString["ProductCategory_Id"] == id)\n        {\n            Label1.ForeColor = System.Drawing.Color.Red;\n        }\n    }\n}	0
17212366	17208790	UTC timestamps for NHibernate Envers revision info	var enversCfg = new FluentConfiguration();\nenversCfg.SetRevisionEntity<DefaultRevisionEntity>(r => r.Id, r=> r.RevisionDate, yourRevisionListener>();	0
26751578	26751523	Get next semicolon after a string in C#	var idx = yourString.IndexOf("unable");\nif (idx != -1)\n{\n    idx = yourString.IndexOf(';', idx);\n    if (idx != -1)\n    {\n        // you found it\n    }\n}	0
5037549	5037518	LINQ to DropDownList with Server.HtmlDecode	foreach (var category in userCategories)\n{\n    CategoryDropDownList.Items.Add(new ListItem(Server.HtmlEncode(category.Category), category.ID.ToString()));\n}	0
16043469	16043387	Change an object in Database	string filmID = comboBox1.SelectedValue.ToString();\nScenario newScenario = new Scenario();\nforeach (Scenario scenario in myDatabase.Scenario\n    .Where(scn => scn.filmID.ToString().Equals(filmId))\n{\n    scenario.SceneWriter.Add(newScenewriter);before\n}\n\nmyDatabase.SaveChanges();	0
6876198	4669392	Get all opened Excel-documents	Microsoft.Office.Interop.Excel.Application oExcelApp;\n\noExcelApp = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");\n\nforeach (Microsoft.Office.Interop.Excel.Workbook WB in oExcelApp.Workbooks) {\n   MessageBox.Show(WB.FullName);\n}\n\noExcelApp = null;	0
33896573	33896193	Suspending a PC	System.Windows.Form	0
4001921	4001908	Get Dictionary key by using the dictionary value	var keysWithMatchingValues = dic.Where(p => p.Value == "a").Select(p => p.Key);\n\nforeach(var key in keysWithMatchingValues)\n    Console.WriteLine(key);	0
24118200	24118035	How to create a Task which accept input arguments	public Task<double[]> ConvertToDouble<T>(T [] input)\n{\n    return new Task<double []> (CovertToDoubleArray ((T[]) item),  intArray) ;\n}	0
6105127	6105101	linq to sql c#: replace a foreign key with its string value and keep the table structure	var query = (\n    from a in db.Record_HoldData\n    join b in db.FlavorTable on\n        a.FlavorId equals b.Id\n    where a.HoldStatus == "Open"\n    select\n        new\n        {\n            a.DateOpened,\n            a.Field1,\n            a.Field2,\n            ...\n            b.FlavorName\n        })\n    .ToList();	0
7275536	7275464	Allow userform input from a foreach loop?	Queue<XmlNode>	0
33622941	33602678	How to Navigate to Pages on ListView ItemSelected while it is in other class file?	void navigatePage_onSelected(object sender, SelectedItemChangedEventArgs args){\n            _menulink menuitem = (_menulink)args.SelectedItem;\n            MasterDetailPage mstr = (MasterDetailPage)(Application.Current.MainPage); // My Application main page is a Masterpage so..\n            if (menuitem._link == "ABOUT FTW") {\n                mstr.Detail = new NavigationPage (new AboutFTW ());\n            }else if(menuitem._link == "I NEED HELP"){\n                mstr.Detail = new NavigationPage (new Entertainment ());\n            }else if(menuitem._link == "HOME"){\n                mstr.Detail = new NavigationPage (new FTWHome ());\n            }\n            // Show the detail page.\n            mstr.IsPresented = false;\n        }	0
3026297	3016508	Total Number of records required in paged .NET datagrid control	protected void MyDataSource_Selected(object sender, ObjectDataSourceStatusEventArgs e)\n{\n    var count = e.ReturnValue as int?;\n    if (count.HasValue)\n        litResults.Text = string.Format("Total results found {0}", count);\n}	0
12970436	12970362	Connection must be valid and open	try\n        {\n            if (this.Connection.State == ConnectionState.Closed)\n                this.Connection.Open();\n            List<Bet> bets = new List<Bet>();\n            using(MySqlDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)){\n\n\n            while (dr.Read())\n            {\n                Bet myBet = new Bet();\n                myBet = FillBetfromRow(dr);\n                bets.Add(myBet);\n            }\n       }\n            return bets;\n        }	0
6552742	6552428	Dynamically creating Table Layout Panel takes too long	public class DoubleBufferedTableLayoutPanel :TableLayoutPanel\n{\n    public DoubleBufferedTableLayoutPanel()\n    {\n        DoubleBuffered = true;\n    }\n}	0
8230563	8230434	Dapper dynamic parameters throw a SQLException "must define scalar variable" when not using anonymous objects	class MyAccount \n{\n    public string Name { get; set; }\n    public int Priority { get; set; }\n}	0
13108675	13103064	How do I save an image url to a local file in Windows 8 c#	private async Task<StorageFile> SaveUriToFile(string uri)\n{\n    var picker = new FileSavePicker();\n\n    // set appropriate file types\n    picker.FileTypeChoices.Add(".jpg Image", new List<string> { ".jpg" });\n    picker.DefaultFileExtension = ".jpg";\n\n    var file = await picker.PickSaveFileAsync();\n    using (var fileStream = await file.OpenStreamForWriteAsync())\n    {\n        var client = new HttpClient();\n        var httpStream = await client.GetStreamAsync(uri);\n        await httpStream.CopyToAsync(fileStream);\n        fileStream.Dispose();\n    }\n    return file;\n}	0
9155185	9154985	Grouping Items In A List View	Dictionary<String, Country> dict = new Dictionary<string, Country>();\ndict.Add("Toronto", Country.Canada);\ndict.Add("New York", Country.US);\ndict.Add("Vancover", Country.Canada);\ndict.Add("Seattle", Country.US);\ndict.Add("Fredericton", Country.Canada);\n\nLookup<Country,String> lookup = (Lookup<Country,String>) dict.ToLookup(pair =>pair.Value, pair => pair.Key);\n\n foreach (var countryGroup in lookup)\n {\n    item = new ListViewItem(countryGroup.Key.ToString());\n    item.SubItems.Add(string.Format("{0}", string.Join(",", countryGroup.Select(s => "@" + s))));\n    lv.Items.Add(item);\n    item = null;\n }	0
21756488	21741131	Using Autofac to inject a dependency into the Main entry point in a console app	public static class Program\n{\n    public static void Main() {\n        var container = ConfigureContainer();\n\n        var application = container.Resolve<ApplicationLogic>();\n\n        application.Run();\n    }\n}\n\npublic class ApplicationLogic\n{\n    private readonly ILog log;\n\n    public ApplicationLogic(ILog log) {\n        this.log = log;\n    }\n\n    public void Run() {\n        this.log.Write("Hello, world!");\n    }\n}	0
3098857	3098703	Populating a dropdownlist control along with "Please select a value" option	ddlFacultyMember.Items.Insert(0, new ListItem("Please Select a Value", "0"));	0
26287283	26284903	Unexpected termination of SSIS when calling it from a stored procedure initiated by a C# service	EXEC [SSISDB].[catalog].[set_execution_parameter_value] \n        @execution_id,  -- execution_id from catalog.create_execution\n        @object_type=50, \n        @parameter_name=N'SYNCHRONIZED', \n        @parameter_value= 0;	0
24384445	24350548	How to send mail in c# instantly or at least perform it in background	Task sendEmail = new Task(() =>\n        {\n            //create the mail message\n            MailMessage mail = new MailMessage();\n\n            //set the addresses\n            mail.From = new MailAddress("me@mycompany.com");\n            mail.To.Add("you@yourcompany.com");\n\n            //set the content\n            mail.Subject = "This is an email";\n            mail.Body = "this is a sample body";\n\n            //send the message\n            SmtpClient smtp = new SmtpClient();\n            smtp.Port = 465;\n            smtp.UseDefaultCredentials = true;\n\n            smtp.Host = "smtp.gmail.com";\n\n            smtp.EnableSsl = true;\n            smtp.Credentials = new NetworkCredential("youGmailAddress@gmail.com", "YourPassword");  \n\n            smtp.Send(mail);\n        });\n\n        sendEmail.Start();	0
24458911	24458599	How can I programmatically bind this CheckBox?	autoScrollBinding.Source = this;	0
26846894	26825984	DbMigration seed sequence contains more than one element	//but two lines below in "OnModelCreating" method in your Context\n\n modelBuilder.Entity<Lookup>().Map<Catalog>(m => m.Requires("IsCatalog").HasValue(true));\n modelBuilder.Entity<Lookup>().Map<CatalogType>(m =>m.Requires("IsCatalog").HasValue(false));\n\n// then :\n context.Lookups.AddOrUpdate(p => new { p.Name , p.IsCatalog},\n        new CatalogType\n        {\n            Name = "General",\n            IsActive = true,\n            Order = 1,\n        },\n        new CatalogType\n        {\n            Name = "Custom",\n            IsActive = true,\n            Order = 2,\n        });\n        //context.SaveChanges(); //if you used base.OnModelCreating(modelBuilder);\n        base.OnModelCreating(modelBuilder); // then you don't need to save	0
14882005	14881863	Linq to SQL in C# Unique data	var res = (from positions in context.Lloyds_ETAs\n          join vessels in context.Lloyds_Vessels on positions.ImoNumber equals vessels.imo_no\n          select new PositionData {\n              ImoNo = positions.ImoNumber,\n              PositionCordinates = positions.AIS_Latest_Position,\n              CompassOverGround = positions.Compass_over_Ground_Heading,\n              VesselId = positions.Vessel_ID,\n              Equipment = vessels.vessel_type,\n              Updated = positions.Last_Place_Location\n           })\n           .GroupBy(x => x.ImoNo)\n           .Select(g => g.OrderByDescending(pd => pd.Updated).First());	0
1079019	1078945	Split a string by semicolons while accounting for escaped characters	System.Data.Common.DbConnectionStringBuilder builder = new System.Data.Common.DbConnectionStringBuilder();\n\n        builder.ConnectionString = "Provider=\"Some;Provider\";Initial Catalog='Some;Catalog';";\n\n        foreach (string key in builder.Keys)\n        {\n            Response.Write(String.Format("{0}: {1}<br>", key , builder[key]));\n        }	0
18723557	18723420	How to make background of my app white?	ThemeManager.ToLightTheme();	0
25164060	24614692	Generate AnyCPU assembly for C# with SWIG	Environment.Is64BitProcess	0
25473426	25471705	2d Array from JSON with MINIJson	int[,] layout = new int[9,9];\n\nvar dict = (Dictionary<string, object>)Json.Deserialize(jsonString); \nvar list = (List<object>)dict["layout"];\n\nfor (int row = 0; row < 9; row++)\n{\n    var items = (List<object>)list[row];\n    for (int col = 0; col < 9; col++)\n    {\n        layout[row, col] = Convert.ToInt32(items[col]);\n    }\n}	0
31159150	31155905	Extract peaks from a signal	[localmax,maxind] = findpeaks(x);\ninversex = 1.01*max(x) - x;\n[localmin,minind] = findpeaks(inversex);\n%//this gives all maxima and minima, now you can compute the width.\n\n%//as for the top 4 peaks, surely you just sort and index 1:4 upon the result or in the beginning.	0
1535072	1535065	Regular expression to get text inside parenthesis	Regex r = new Regex(@"^value\((.*)\)\.$");	0
19078409	19078135	C# Passing an array as a parameter?	var query = from p in Process.GetProcesses()\n            orderby p.ProcessName\n            select p;\n\nList<XElement> content = new List<XElement>();\nforeach (var item in query)\n{\n    content.Add(new XElement("Process",\n        new XAttribute("Name", item.ProcessName),\n        new XAttribute("PID", item.Id)));\n}\n\nvar paramArr = content.ToArray();\nvar rootElement = new XElement("Processes", paramArr); // create one root element\nXDocument doc = new XDocument(rootElement);	0
17632975	17558867	Using GroupedItemsPage as main Menu	protected override void OnNavigatedTo(NavigationEventArgs e)\n        {\n            this.DefaultViewModel["Groups"] = e.Parameter;\n}	0
11399963	11399934	7-zip (7za.EXE) in C# to archive files of same name & store folder information	path.Substring(3)	0
4564701	4564318	C# XML parsing - skipping null tags in some 'items'	from ev1 in document.Descendants("channel").Elements("item")\n    .Where(e => e.Element(georss + "point") != null)	0
21363583	21363540	Control 'webBrowser1' accessed from a thread other than the thread it was created on	form2.Show();\n   Encoding charset = Encoding.GetEncoding("utf-8");\n   HttpWebRequest SMSRequset =  (HttpWebRequest)WebRequest.Create("http://www.iam.ma/_layouts/SharepointFreeSms/EnvoyerSms.aspx");  \n   SMSRequset.Method = "GET";\n   SMSRequset.CookieContainer = cookies;\n   HttpWebResponse SMSResponse = (HttpWebResponse)SMSRequset.GetResponse();\n   System.IO.StreamReader reader2 = new System.IO.StreamReader(SMSResponse.GetResponseStream(), charset);\nform2.webBrowser1.Invoke((MethodInvoker)delegate\n{\n   form2.webBrowser1.DocumentText = reader2.ReadToEnd();\n});	0
4032338	4032252	Pass array as individual values to params	public static IQueryable Where(this IQueryable source, string predicate, params object[] values)	0
1019499	1019434	How can I make LINQ to SQL use a connection string which is being modified at runtime?	ConnectionStringSettings settings = ConfigurationManager.ConnectionStrings["LoremIpsum"];\nSqlConnectionStringBuilder builder;\nLINQTOSQLDataClassDataContext db;\n\nif (null != settings) \n{   \n    string connection = settings.ConnectionString;  \n    builder = new SqlConnectionStringBuilder(connection);\n\n   // passwordTextBox being the control where joe the user actually enters his credentials\n\n    builder.Password =passwordTextBox.Text;  \n    db = new LINQTOSQLDataClassDataContext(builder.ConnectionString);\n } }	0
10794412	10794349	How can i get data from a dataset into a list?	foreach (DataRow dr in prfLogic.GetAllProductFamilies())\n{\n   foreach(DataColumn dataColumn in myDataTable.Columns)\n    {\n        string fieldValue = dr[dataColumn].ToString();   \n    }\n}	0
17465015	17464640	Prevent form from going into windowed mode	public class Form1 {\n  public Form1(){\n      InitializeComponent();\n      WindowState = FormWindowState.Maximized;\n      Load += (s,e) => {\n         MaximizeBox = false;        \n      };\n  }\n  bool hitControlButtons;\n  protected override void WndProc(ref Message m)\n  {\n     if ((!hitControlButtons) && (m.Msg == 0xa3 || m.Msg == 0xa1))//WM_NCLBUTTONDBLCLK and WM_NCLBUTTONDOWN\n     {                \n        return;\n     }\n     if (m.Msg == 0xA0)//WM_NCMOUSEMOVE\n     {\n        int wp = m.WParam.ToInt32();                \n        hitControlButtons = wp == 8 || wp == 20 || wp == 9;//Mouse over MinButton, CloseButton, MaxButton                               \n     }\n     base.WndProc(ref m);            \n  }\n}	0
23872669	23872396	Entity Framework with DAL C#	public interface IMyGenericDBProcessor\n{\n    void AddToDB<T>(T Record) where T : class;\n}\n\npublic class MyDBProcessor : IMyGenericDBProcessor \n{\n    public void AddToDB<T>(T record) where T : class\n    {\n        using(var tp = new tpEntities())\n            tp.Set<T>().Add(record);\n    }\n}	0
34003990	34003707	How to get word and word group starting from beginning in a string?	public IEnumerable<string> GetGroups(string str)\n{\n    var items = str.Split(new[] { " " }, StringSplitOptions.RemoveEmptyEntries);\n\n    var groups = new List<string>(items);\n\n    for (int i = 1; i < items.Count(); i++)\n    {\n       groups.Add(string.Join(" ", items.Where((s, idx) => idx <= i)));\n    }\n\n    return groups;\n}	0
15517199	15517142	Retrieving files stored on Windows 8 Device from "Metro" app	/// <summary>\n    /// \n    /// </summary>\n    /// <param name="identity"></param>\n    /// <returns></returns>\n    public static async Task<IStorageFile> FileFromPicker(string identity)\n    {\n        FileOpenPicker picker = new FileOpenPicker();\n\n        setFileTypes(picker);\n\n        picker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;\n        picker.ViewMode = PickerViewMode.Thumbnail;\n        picker.SettingsIdentifier = identity;\n\n        var storageFile = await picker.PickSingleFileAsync();\n\n        return storageFile;\n    }	0
31754198	31752962	How to read float data from a file in F#	open System\nopen System.IO    \n\nlet readFloats filePath = \n    let strs = File.ReadLines(filePath) // Read file line by line\n    strs |> Seq.map (fun str -> System.Double.TryParse(str)) // TryParse returns pair (Boolean * float value). Boolean is true if string parsed correctly \n         |> Seq.filter (fun (success, _) -> success) // filters out wrong  (not parsed strings)\n         |> Seq.map snd // transforms sequence of pairs (bool * float) into float only	0
12692207	12692010	C# GridViews - Make the cells in one column link to another page when clicked	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n            e.Row.Cells[0].Text = "<a href=''>" + e.Row.Cells[0].Text + "</a>";\n}	0
22176610	22176203	custom Iterator Index out of bounds	if (nextIndex >= courseView.Count ) //to last element, yours is at second last.\n    {\n        currIndex = nextIndex;\n        return false;// make it false, it should terminate and end loop . \n    }	0
4059620	4059512	How to set focus to a control in a Windows Forms application?	Public Sub New()\n    InitializeComponent()\n    MyDropDownList.Select()\nEnd Sub	0
29918500	29918302	Creating a statusfield for users	label_status_title.Text = "Status: changing files.\nfiles changed: " + i + "/" + d.Count + " files.";\nlabel_status_title.Refresh(); //added	0
4515908	4515876	How to Union List<List<String>> in C#	YourList.SelectMany(l=>l).Distinct()	0
28675282	28672865	Using Google API to Query Date in Spreadsheet	listQuery.SpreadsheetQuery = "date=2015-01-05";	0
25527317	25527251	How to sort DataTable Rows without creating DataView?	var newTable = rows.CopyToDataTable();	0
23080282	23080165	How to properly set a one-to-one relationship?	public class User\n    {\n        public User() \n        { \n        }\n\n        public int idUser; { get; set; }\n        [Required]\n        public string UserName { get; set; }\n\n\n        public virtual Computer Computer{ get; set; }\n\n    }\n\n\npublic class Computer\n    {\n        public Computer() \n        {\n        }\n        [Key, ForeignKey("User")]\n        public int idUser{ get; set; }\n\n        public string ComputerName {get;set;}\n\n        public virtual User User { get; set; }\n    }	0
34274104	34274030	C# How to insert items at specific index in nullable bool List	List<bool?> bools	0
13789954	13789893	How extension properties syntax would be look like	public static TimeSpan Minutes[this int i]\n{\n    get { return new TimeSpan(0, i, 0); }\n}	0
18764748	18764067	Order By on the Basis of Integer present in string	var maxLen = cx.Classes.Max(x => x.Name.Length);\n        var query =  cx.Classes.Select(x => x.Name).OrderBy(x => x.PadLeft(maxLen));	0
30357088	30357001	Error with indenxing with [] in c#	int average(int[] a, int k)\n{\n    int average, s, i, n;\n\n    s = 0;\n    for (i = 0; i < k; i++)\n    {\n        a[i] = Convert.ToInt32(lblSortiranNiz.Items[i]);\n        s = s + a[i];\n    }\n    average = s / k;\n    return average;\n}	0
3894593	3894561	Sorting array of type of object respecting to one of the object values	Array.Sort(array, (s1, s2) => s1.Name.CompareTo(s2.Name));	0
2946713	2946380	Save binarydata into a image file in c# / silverlight 3	System.IO.File.WriteAllBytes("c:\\YourFile.png", binaryData);	0
14785907	14785855	Ninject in a three tier application	Bind<ICustomerRepository>().To<CustomerRepository>();	0
6559253	6559190	OleDbCommand Stored Procedure Cannot Find Access Query	[Append Me]	0
3874478	3874471	Grouping lambda	batches.GroupBy(x => x.Batch, x => x.Amount).Select(g => new {\n    Batch = g.Key,\n    Amount = g.Sum()\n});	0
30355582	30323061	twitter get user profile data	TwitterCredentials.SetCredentials("Access_Token", "Access_Token_Secret", "Consumer_Key", "Consumer_Secret");\nvar user =  User.GetUserFromScreenName("<username>");	0
4604918	4604726	c# email object to stream to attachment	...\n\nbyte[] data = ASCIIEncoding.Default.GetBytes(ieLog.FirstName + "." + ieLog.LastName);\n\nusing(MemoryStream ms = new MemoryStream(data))\n{\n    mail.Attachments.Add(new Attachment(ms, "myFile.csv", "text/csv" ));\n\n    SmtpClient smtp = new SmtpClient("127.0.0.1");\n    smtp.Send(mail);   \n}	0
2136869	2136857	Using HttpWebRequest to POST to a form on an outside server	using (var resp = myRequest.GetResponse())\n{\n    using (var responseStream = resp.GetResponseStream())\n    {\n        using (var responseReader = new StreamReader(responseStream))\n        {\n        }\n    }\n}	0
2325811	2325587	Start External Process with Impersonate Issue	Debug.Print()	0
18965144	18965107	Kill process by part of name	var processes = Process.GetProcesses();\nforeach(var p in processes.Where(proc => proc.ProcessName.IndexOf(searchString, StringComparison.CurrentCultureIgnoreCase) > -1))\n   p.Kill();	0
13979832	13979096	How to get sub-directory names and files from a folder dragged and dropped onto an application	public void ProcessFolder(DirectoryInfo dirInfo)\n{\n    //Check for sub Directories\n    foreach (DirectoryInfo di in dirInfo.GetDirectories())\n    {\n        //Call itself to process any sub directories\n        ProcessFolder(di);\n    }\n\n    //Process Files in Directory\n    foreach (FileInfo fi in dirInfo.GetFiles())\n    {\n        //Do something with the file here\n        //or create a method like:\n        ProcessFile(fi)\n    }\n} \n\npublic void ProcessFile(FileInfo fi)\n{\n    //Do something with your file\n    Debug.Print(fi.FullName);\n    //...\n}	0
17474234	17474151	Removing a letter before a capital letter	(?<=\s)x(?=[A-Z])	0
13100697	13099874	how to give confirm message box when selecting previous date in asp.net	void Selection_Change(Object sender, EventArgs e) \n{\n         if(Calendar1.SelectedDate < Date.Now)\n         {\n             Response.Write("<script language=javascript>alert('previous date selected');</script>);\n         }\n}	0
6077753	6077710	Help with a regular expression in C#	(\[[^\]]*\])	0
6390961	6390904	Deleting row from datatable in C#	DataRow[] drr = dt.Select("Student=' " + id + " ' "); \n    for (int i = 0; i < drr.Length; i++)\n        drr[i].Delete();\n    dt.AcceptChanges();	0
23348316	23343296	Space represented by a single Kinect pixel at a given depth	2 sin(PI VFOV / 360) D Y\nX = --------------------------\n              VRES	0
3065236	3065186	C# - High Quality Byte Array Conversion of Images	Convert.ToBase64String	0
22540569	22540265	How to add/store coordinate values to a list ?	List<GeoCoordinate> mycoord = new List<GeoCoordinate>();\nmycoord.add(MyGeoPosition);	0
4196416	4196274	LINQ to XML Select Nodes by duplicate child node attributes	var whoHasPager = from teamMember in data.Elements("Employee")\n                  where teamMember.Elements("Phone").Any(x => x.Attribute("Type").Value == "Pager")\n                  select teamMember;	0
25374721	25374683	Insert into a certain position in a string	string s = "MOT1-G-PRT45-100";\nint index = ... // position to insert\nstring res = s.Insert(index, c + separator);	0
11449355	11449039	Delete repeating data C# to SQL conversion	;WITH a AS (\n    SELECT  *,\n            ROW_NUMBER() OVER (PARTITION BY email ORDER BY Id) RowNum\n    FROM    UserBase\n)\n-- deleted rows will be:\nSELECT  *\n--DELETE \nFROM    a\nWHERE   a.RowNum <> 1	0
28545414	28539595	How to get access to children of WindowsPhone page?	var currentPage = ((PhoneApplicationFrame)Application.Current.RootVisual).Content as PhoneApplicationPage;\n        for (int i = 0; i < VisualTreeHelper.GetChildrenCount(currentPage); i++)\n        {\n            DependencyObject child = VisualTreeHelper.GetChild(currentPage, i);\n\n            if (child is System.Windows.Controls.Control)\n            {\n                // do work\n            }\n            else if (child is System.Windows.FrameworkElement)\n            {\n                // do work\n            }\n            if (VisualTreeHelper.GetChildrenCount(child) > 0)\n            {\n                enumChildren(child); // recur. enumerate children\n            }\n        }	0
894271	894263	How to identify if a string is a number?	int n;\nbool isNumeric = int.TryParse("123", out n);	0
15709124	15708575	Is it possible to get list of query string parameters and change 1 of the parameter and pass as parameter	Request.QueryString	0
9106302	9106252	How to capture WorkBook Name in an .xls file?	connection.Open();\n        DataTable schemaTable = connection.GetOleDbSchemaTable(\n            OleDbSchemaGuid.Tables,\n            new object[] { null, null, null, "TABLE" });\n foreach (DataRow row in schemaTable.Rows )\n  {\n     Console.WriteLine(row["TABLE_NAME"]);\n   }	0
7028999	7028930	Ignore milliseconds when comparing two datetimes	dt = dt.AddMilliseconds(-dt.Millisecond);	0
7177312	7177048	Extracting Numbers From A String	string DiagnosesString  =  "250.00 03 350.0001 450.00 01 550.00 02";\n\n       string DiagnosisCodestemp = DiagnosesString.Replace(" 01 ", " ").Replace(" 02 ", " ").Replace(" 03 ", " ").Replace(" 04 ", " ").Replace(" 05 ", " ").Replace(" 06 ", " ").Replace(" 07 ", " ");\n\n        string[] DiagnosisCodesParts = DiagnosisCodestemp.Split();\n\n        foreach (var item in DiagnosisCodesParts)\n\n        {\n\n            string[] parts = item.Split('.');\n            string num = parts[1];\n            string finalValue = string.Empty;\n\n            if (num.Length > 2)\n            {\n                num = num.Replace(num, "00");\n                finalValue =  parts[0]+"."+num;\n            }\n            else\n            {\n                finalValue = parts[0] + "." + num;\n            }\n\n            list.Add(finalValue);\n        }	0
17871098	17868025	Click on a picturebox and go to website	![private void FrmWeb_Btn_Click(object sender, EventArgs e)\n        {\n\n\n            PictureBox PB = new PictureBox();\n\n            PB.ImageLocation =  "https://si0.twimg.com/profile_images/378800000038434114/f676cbea6f8500c9c15529e1d5e548c1_reasonably_small.jpeg";\n            PB.Size = new Size(100, 100);\n            Controls.Add(PB);\n\n            PB.Click +=new EventHandler(PB_Click); \n\n\n        }\n\n        protected void PB_Click(object sender, EventArgs e)\n        {\n\n            webBrowser1.Navigate("http://twit.tv/");\n\n        }][2]	0
20243844	20243576	A factor while making at runtime NLog config user-define	LogManager.Configuration = LogManager.Configuration.Reload();	0
20668037	20667980	Initializing an array of Images	new Image[] { /* stuff in collection */ }	0
11323079	11323040	Change an Image to Byte, for file *within* project	string path = Server.MapPath("images/dashboard/myvacstatus-am.png")	0
6123254	6088241	Is there a way to check whether unicode text is in a certain language?	public bool IsChinese(string text)\n{\n    return text.Any(c => c >= 0x20000 && c <= 0xFA2D);\n}	0
21793625	21792642	Parse Json using Json Net and C# to fill a dropdown	JArray jArray = JArray.Parse(jsonStr);\n\nbool isDefault;\nstring defaultValue;\nforeach (JObject jObject in jArray.Children<JObject>())\n{\n    isDefault = false;\n\n    // check if current jObject contains a property named "selected"\n    // and if the value is true\n    JProperty p = jObject.Properties().SingleOrDefault(x => x.Name == "selected");\n    if (p != null && (bool)p.Value == true)\n    {\n        isDefault = true;\n    }\n\n    foreach (JProperty jProperty in jObject.Properties())\n    {\n        string name = jProperty.Name.Trim();\n        string value = jProperty.Value.ToString().Trim();\n\n        if (name != "selected")\n        {\n            drpValues.Items.Add(new RadComboBoxItem(name, value));\n            if (isDefault)\n            {\n                defaultValue = value;\n            }\n        }\n    }\n}\n\n// set the dropdown selected item\nRadComboBoxItem itemToSelect = drpValues.FindItemByValue(defaultValue);\nitemToSelect.Selected = true;	0
13549914	13525993	Creating a custom application in Umbraco 4.8+	using umbraco.businesslogic;\nusing umbraco.interfaces;\n\n[Application("myApp", "My App", "myapp.gif")]\npublic class Class1 : IApplication \n{\n    public Class1()\n    {\n        //\n        // TODO: Add constructor logic here\n        //\n    }\n}	0
22650048	22649917	Show dates in SQL in asp:Calendar	protected void Calendar1_DayRender(object sender, DayRenderEventArgs e)\n{\n    // Disable the date being rendered if it is not in the DB-returned dates (as\n    // List<DateTime> _databaseDates).\n    if (!_databaseDates.Contains(e.Day.Date))\n    {\n        e.Day.IsSelectable = false;\n        e.Cell.ForeColor = Color.Gray; // or e.Cell.Font.Strikeout = true;\n    }\n}	0
10247881	10247805	Object Data Source function returning only 1 value	public List<Employees> GetEmployees()\n{\n    ..\n    List<Employees> emps = new List<Employees>();\n    Employees emp = null;\n\n    while (..)\n    {\n        emp = new Employees();\n        ..\n        emps.Add(emp);\n    }\n\n    return emps;\n}	0
32242813	32242175	Get Resutls from XML with more than one line	var orderLines = xDoc\n   .Element(nsp + "UniversalInterchange")\n   .Element(nsp + "Body")\n   .Element(nsp + "UniversalShipment")\n   .Element(nsp + "Shipment")\n   .Element(nsp + "Order")\n   .Element(nsp + "OrderLineCollection")\n   .Elements(nsp + "OrderLine");\n\n// 1, 2\nvar lineNumbers = orderLines.Select(x => x.Element(nsp + "LineNumber").Value);	0
25201768	25201700	Using BindableCollection outside ViewModel	var myObservableList = new ObservableCollection<MyModelType>(myModel.NiceList);	0
14296593	14295148	Hiding system and hidden files in a treeview file explorer	DirectoryInfo d = new DirectoryInfo(@"c:\");\nDirectoryInfo[] dInfo = d.GetDirectories()\n                          .Where(di => !di.Attributes.HasFlag(FileAttributes.System))\n                          .Where(di => !di.Attributes.HasFlag(FileAttributes.Hidden))\n                          .ToArray();	0
13891921	13885783	Query or algorithm to generate a structure to populate a tree (C#, LINQ)	public class BlogEntyTreeItem\n{\n   public string Text { set; get; }\n   public string URL { set; get; }\n   public List<BlogEntyTreeItem> Children { set; get; }\n\n   public List<BlogEntyTreeItem> GetTree()\n   {\n       NWDataContext db = new NWDataContext();\n       var p = db.Posts.ToList();\n\n       var list = p.GroupBy(g => g.DateCreated.Year).Select(g => new BlogEntyTreeItem\n       {\n           Text = g.Key.ToString(),\n           Children = g.GroupBy(g1 => g1.DateCreated.ToString("MMMM")).Select(g1 => new BlogEntyTreeItem\n           {\n               Text = g1.Key,\n               Children = g1.Select(i => new BlogEntyTreeItem { Text = i.Name }).ToList()\n           }).ToList()\n       }).ToList();\n\n       return list;        \n   }\n}	0
5897563	5897432	How to remove tree node and move its node node upwards?	if (tree.Nodes.Contains(theNode))\n        {\n            TreeNodeCollection childNodes = theNode.Nodes;\n            tree.Nodes.Remove(theNode);\n            foreach (TreeNode child in childNodes)\n            {\n                tree.Nodes.Add(child);\n            }\n        }	0
14929768	14929674	How to find primary key(s) of the table in database C#	SHOW INDEX	0
23660181	23650263	Selenium RC find element that have a specific string at the start of the class	driver.FindElement(By.CssSelector(".dummy"))	0
9133062	9133031	How do I use LINQ to reduce a collection of strings to one delimited string?	string result = string.Join(";", fooList.Where(x=>x.property == "bar").Select(x=>x.title));	0
6319567	6319546	How to color different words in a RichTextBox with different colors?	txtRichTextBox.Select(yourText.IndexOf("portion"), "portion".Length);\ntxtRichTextBox.SelectionColor = YourColor;\ntxtRichTextBox.SelectionFont = new Font("Times New Roman",FontStyle.Bold);	0
25108543	25108458	Best method for comparing XML with string	foreach (XElement element in xmlDocument.Elements())\n{\n    if (textBox3.Text.ToString() == element.Element("NAAM").Value)\n    {\n        PDFLocation = element.Element("NAAM").Value;\n        pictureBox1.Image = pdfhandler.GetPDFthumbNail(PDFLocation);\n        textBox4.Text =\n                        element.Element("Title").Value + "\r\n" +\n                        element.Element("Brand").Value + "\r\n" +\n                        element.Element("Type").Value + "\r\n"\n                        // access rest of properties...\n    }\n}	0
1625852	1625846	Difference between ReadOnlyCollection string[] in the context of collection	strList[2] = "Pear";	0
34400514	34400275	Winforms dot.net Detect if more than x alphabets of string one are present in string two & vice versa	String.Intersect	0
15559162	15558730	DataGridView Select command with parameters	YourDataSource.YourTableDataTable anything= new YourDataSource.YourTableDataTable();\n\n    yourdataadapter.fill(anything,parametervalue.tostring());\n     DataGridView1.datasource= anything;	0
23865989	23865327	How to get top 10 Cases from gridview?	List<double> nums = new List<double>();\n\n        for (int i = 0; i < grvData.Rows.Count; i++)\n        {\n            if (grvData.Rows[i].Cells[23].Text == "OPEN" && grvData.Rows[i].Cells[28].Text == "NO")\n            {\n                nums.Add(Convert.ToDouble(grvData.Rows[i].Cells[18].Text));\n            }\n        }\n\n        nums = nums.OrderByDescending(n => n).ToList();\n\n        NONSPR4.Text = nums[0].ToString();\n        NONSPR8.Text = nums[1].ToString();\n        NONSPR12.Text = nums[2].ToString();\n        NONSPR16.Text = nums[3].ToString();\n        NONSPR20.Text = nums[4].ToString();\n        NONSPR24.Text = nums[5].ToString();\n        NONSPR28.Text = nums[6].ToString();\n        NONSPR32.Text = nums[7].ToString();\n        NONSPR36.Text = nums[8].ToString();\n        NONSPR40.Text = nums[9].ToString();	0
5948757	5948457	xml file compare	var elements1=(from e in file1.Element("in_mind").Descendants() select e.Name).ToList();\nvar elements2=(from e in file2.Element("in_mind").Descendants() select e.Name).ToList();\n\nfor(int i=0;i<elements1.Count;i++)\n{\n    if(elements1[i]!=elements2[i])\n    {\n        return false;\n    }\n}\n\nreturn true;	0
13632134	10625110	SoundClip only plays ONCE on button_Click	private void SoundClip_MediaEnded(object sender, Windows.UI.Xaml.RoutedEventArgs e) {\n  SoundClip.Stop();\n }	0
22045059	22044290	Convert a List contaning List<double> to single flatten array	public static void Main()\n{\n    List<List<double>> listOfLists = new List<List<double>>();\n\n    listOfLists.Add(new List<double>() { 1, 2, 3 });\n    listOfLists.Add(new List<double>() { 4, 6 });\n\n    int flatLength = 0;\n    foreach (List<double> list in listOfLists)\n        flatLength += list.Count;\n\n    double[] flattened = new double[flatLength];\n\n    int iFlat = 0;\n\n    foreach (List<double> list in listOfLists)\n        foreach (double d in list)\n            flattened[iFlat++] = d;\n\n    foreach (double d in flattened)\n        Console.Write("{0} ", d);\n\n    Console.ReadLine();\n}	0
17538689	17538658	Setting a working directory for a process to the exe's path?	string myAppPath = System.Reflection.Assembly.GetEntryAssembly().Location;\nif (File.Exists(Path.Combine(myAppPath, pathToExe)))\n{\n    workDir = Path.GetDirectoryName(Path.Combine(myAppPath, pathToExe));\n}\nelse \n{\n    // Use the referenced article to iterate thru System PATH to find the right path\n}	0
8261858	8255746	can not dispose controls in splitcontainer	for (int nI = splitContainerMain.Panel2.Controls.Count - 1; nI >= 0; nI--) \n { \n     splitContainerMain.Panel2.Controls[nI].Dispose();\n }	0
5805287	5804445	Comparing base types in reflection	if (typeof(ISomeInterface).IsAssignableFrom(passedInParameter.GetType()))\n{\n}	0
7962375	7961949	How do I have similar multiple panels of GUI to appear on my Windows Form Application	for(int i = 0; i < panels.length; i++){\n    AddPanel(panels[i], i);\n}\n\nAddPanel(System.Drawing.Point point, int tabIndex){\n    Panel panel = new Panel();\n    this.Add(panel);\n    panel.Controls.Add(new Button());\n    panel.Controls.Add(new Label("Image"));\n    panel.Controls.Add(new Label("Name"));\n    panel.Controls.Add(new Label("linkName"));\n    panel.Controls.Add(new Label("linkLocation"));\n    panel.Controls.Add(new Label("location"));\n    panel.Location = point;\n    panel.Name = "panel" + i.ToString();\n    panel.Size = new System.Drawing.Size(506, 100);\n    panel.TabIndex = tabIndex;\n}	0
20467738	20467710	select a data in a group which is the newest by linq	var query  = dbContext.Users\n                 .GroupBy(u => u.Department)\n                 .Select(g => g.OrderByDescending(u => u.AddedOn).First());	0
8245493	8232650	How to get the right namespace output	[XmlSerializerFormat]	0
18027964	18027898	how to generate next ID from database	private string genNextId()\n{\n    var id = (from a in dc.nasabahs\n              select a.nomor_nasabah).Max();\n\n    return id.ToString();\n}	0
29102584	29102410	Replacing nulls in table with space	ds.Tables[0].Columns.Add("AverageCostText", typeof(String));\nforeach (DataRow row in ds.Tables[0].Rows)\n{\n     row["AverageCostText"] = (row["AverageCost"] == DBNull.Value) ? string.Empty : string.Format("{0}", row["AverageCost"]);\n}	0
21407139	21406877	Bind to a MainPage Property out of DataTemplate	((ChangeDateToFontWeightConverter)this.Resources["ChangeDateToFontWeightConverter"]).MyCustomProperty = myCacheObject;	0
12103912	12103788	Using Thread in a window 8 application	var timer = new DispatcherTimer();\ntimer.Interval = TimeSpan.FromSeconds(1);\ntimer.Tick += OnTimerTick;\n\n...\nprivate void OnTimerTick(object sender, object e)\n{\n    // do somthing\n}	0
9445256	9444033	TreeView Selecting Parent nodes of a child, and childes of a selected parent	private bool updatingTreeView;\n\nprivate void treeView1_AfterCheck(object sender, TreeViewEventArgs e)\n{\n    if (updatingTreeView) return;\n    updatingTreeView = true;\n    CheckChildren_ParentSelected(e.Node, e.Node.Checked);\n    SelectParents(e.Node, e.Node.Checked);\n    updatingTreeView = false;\n}	0
5144723	5144344	a generic sort by string field method	sort(listOfFoos, o => ((Foo) o).name());	0
1751446	1732140	C#: Problem displaying tooltip over a disabled control	void OrderSummaryDetails_MouseMove(object sender, MouseEventArgs e)\n{\n      Control control = GetChildAtPoint(e.Location);\n      if (control != null)\n      {\n          string toolTipString = mFormTips.GetToolTip(control);\n          this.mFormTips.ShowAlways = true;\n          // trigger the tooltip with no delay and some basic positioning just to give you an idea\n          mFormTips.Show(toolTipString, control, control.Width / 2, control.Height / 2);\n      }\n}	0
6889211	6889168	How Can I Remove Event?	Button btn = new Button();\n        this.Controls.Add(btn);\n        btn.Click += (o, x) =>\n        {\n            Button b = o as Button;\n            FieldInfo eventclick = typeof(Control).GetField("EventClick", BindingFlags.Static | BindingFlags.NonPublic);\n            object eventValue = eventclick.GetValue(b);\n            PropertyInfo events = b.GetType().GetProperty("Events", BindingFlags.NonPublic | BindingFlags.Instance);\n            EventHandlerList eventHandlerList = (EventHandlerList)events.GetValue(b, null);\n            eventHandlerList .RemoveHandler(eventValue, eventHandlerList [eventValue]);\n            MessageBox.Show("Test");\n        };	0
1651545	1651504	C#: Snippet extraction based on search term on a single document	int start = -1;\nint index = str.IndexOf(search);\nwhile (index != -1)\n{\n    print str.Substring(index-100, index+100);\n    index = str.IndexOf(search, index);\n}	0
17545793	17545175	c# Soap Client Issue - more than one endpoint configuration for th at contract was found	ServiceReference1.imail_apiSoapClient soapClient = \nnew ServiceReference1.imail_apiSoapClient("imail_apiSoap");	0
6546148	6546114	Empty elements in C# byte array	Byte[] array = new Byte[64];\n\nArray.Clear(array, 0, array.Length);	0
3913154	3913054	Swap Integer variables without using any assignment	Interlocked.Exchange	0
29489858	29489392	Internet explorer Compatibility with css3 and HTML5	internal static bool GetIsCompatibleIEVersionInstalled(int minimumRequiredVersion)\n{\n    var compatibleIEVersionInstalled = false;\n\n    var key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer");\n\n    var fullVersion = (string)key.GetValue("Version");\n\n    int majorVersion;\n\n    if (int.TryParse(fullVersion.Split('.').First(), out majorVersion))\n    {\n        compatibleIEVersionInstalled = majorVersion >= minimumRequiredVersion;\n    }\n\n    return compatibleIEVersionInstalled;\n}	0
31212227	31211677	Find All groups that a group is a member of recursively and show as a tree	class Program\n{\n    static void Main(string[] args)\n    {\n        using (var context = new PrincipalContext(ContextType.Domain))\n        using (var user = UserPrincipal.Current)\n        using (var userGroups = user.GetGroups())\n        {\n            PrintGroups(userGroups, 0);\n        }\n        Console.ReadLine();\n    }\n\n    static void PrintGroups(PrincipalSearchResult<Principal> groups, int level)\n    {\n        foreach (var group in groups)\n        {\n            Console.Write(new string('-', level * 3));\n            Console.WriteLine(group.Name);\n            using (var groupGroups = group.GetGroups())\n            {\n                PrintGroups(groupGroups, level + 1);\n            }\n        }\n    }\n}	0
18364787	18342309	Deleting Grid View Row data wrongly Windows Form My Code Attached?	dataGridView1.DataSource = null;\n        dataGridView1.Columns.Clear();\n        dtCompanyInfo = GetCompanyInfo();\n        if (dtCompanyInfo.Rows.Count > 0)\n        {\n            dataGridView1.DataSource = dtCompanyInfo;\n            DataGridViewCheckBoxColumn checkColumn = new DataGridViewCheckBoxColumn();\n            checkColumn.Name = "";\n            checkColumn.HeaderText = "Select";\n            checkColumn.Width = 50;\n            checkColumn.ReadOnly = false;\n            checkColumn.FillWeight = 10; //if the datagridview is resized (on form resize) the checkbox won't take up too much; value is relative to the other columns' fill values\\\n            dataGridView1.Columns.Add(checkColumn);\n\n        }\n\n    }	0
6405343	6405311	C# - How to implement DateTime.TryParse for 24 hour time format	void textBox1_Validating(object sender, CancelEventArgs e)\n    {\n        DateTime dateEntered;\n\n        if (DateTime.TryParseExact(textBox1.Text, "HH:mm", System.Globalization.CultureInfo.CurrentCulture, System.Globalization.DateTimeStyles.None, out dateEntered))\n        {\n            MessageBox.Show(dateEntered.ToString());\n        }\n        else\n        {\n            MessageBox.Show("You need to enter valid 24hr time");\n        }\n\n    }	0
17108449	17108399	Dictionary<int, List<string>>	------ Returns a list from the dictionary\n         |  --- Returns an item from the list\n         |  |\n         v  v\nfileList[0][0] // First item in the first list\nfileList[1][0] // First item in the second list\nfileList[1][1] // Second item in the second list\n// etc.	0
11395573	11395415	How to deal with memory stack overload	var stackSize = 10000000;\nvar thread = new Thread(new ThreadStart(StartDetection), stackSize);	0
17956194	17955960	windows phone data binding listpicker to List of Strings	public List<String> m_Distances = new List<String>();\npublic List<String> Distances\n{\n    get\n    {\n        return m_Distances;\n    }\n}\n\nlistPickerDistance.ItemsSource = Distances;\n\n<toolkit:ListPicker x:Name="listPickerDistance">\n\n</toolkit:ListPicker>	0
9486226	9486087	How to mock ConfigurationManager.AppSettings with moq	public class Configuration: IConfiguration\n{\n    public User\n    {\n        get{ \n               return ConfigurationManager.AppSetting["User"];\n       }\n    }\n}	0
30758240	30757927	Add Multidimensional Array To List	for (int i = 0; i < columns; i++)\n{\n    double[] column = Enumerable.Range(0, rows)\n        .Select(row => values[row, i]).ToArray();\n    doubleList.Add(column);\n}	0
33543697	33543556	I get a javascript code stored in string format want to convert to pure javascript	var string="function sum(){return 'sum'}";\neval(string);	0
7405559	7405442	Binding results of an linq to xml query to the same gridview	var source = new BindingSource { DataSouce = query1.Concat(query2)\n                                                   .Concat(query3) };\ndataGridView1.DataSource = source;	0
33292111	33292038	Button clicks check boxes based on if statement results	private void EnDis(object sender, RoutedEventArgs e)\n{\n    var button = (Button)sender;\n    if(button.Name == "btnEnable_1")\n    {\n        chk_1.IsChecked = true;\n        chk_2.IsChecked = true;\n        chk_3.IsChecked = true;\n        chk_4.IsChecked = true;\n    }\n        if(button.Name == "btnDisable_1")\n    {\n        chk_1.IsChecked = false;\n        chk_2.IsChecked = false;\n        chk_3.IsChecked = false;\n        chk_4.IsChecked = false;\n    }\n\n    if(button.Name == "btnEnable_2")\n    {\n        chk_5.IsChecked = true;\n        chk_6.IsChecked = true;\n        chk_7.IsChecked = true;\n        chk_8.IsChecked = true;\n    }\n\n}	0
10564256	10309643	deserialize json array to list wp7	[DataContract] \npublic class mainresponse\n {\n [DataMember]\n public resultmap arrayelement { get; set; }\n }  \n [DataContract]\n public class resultmap \n{\n [DataMember] \n public string substringhere { get; set; } \n }     \n var djson = new DataContractJsonSerializer(typeof(Mainresponse));\n var stream = new MemoryStream(Encoding.UTF8.GetBytes(responsestring));\n mainresponse result = (mainresponse)djson.ReadObject(stream);	0
22894290	22894176	Code to check 30 days trial for my application	if (day > 30)\n{\n    if (MessageBox.Show("Trial expired. Visit site to purchase license?",\n        "Trial Expired!", MessageBoxButtons.YesNo) == DialogResult.Yes)\n    {\n        Process.Start("http://www.yourwebsite.com");\n    }\n\n    Environment.Exit(0);\n}	0
6065757	6065618	How Start a window with Main() in Console Project.?	class Program {\n    [STAThread]\n    public static void Main() {\n        var app = new Application();\n        app.Run(new MainWindow());\n    }\n}	0
16044521	16044205	Installing and Running WCF Service inside a Windows Service	// Provide the ProjectInstaller class which allows \n// the service to be installed by the Installutil.exe tool\n[RunInstaller(true)]\npublic class ProjectInstaller : Installer\n{\n    private ServiceProcessInstaller process;\n    private ServiceInstaller service;\n\n    public ProjectInstaller()\n    {\n        process = new ServiceProcessInstaller();\n        process.Account = ServiceAccount.LocalSystem;\n        service = new ServiceInstaller();\n        service.ServiceName = "WCFWindowsServiceSample";\n        Installers.Add(process);\n        Installers.Add(service);\n    }\n}	0
4871080	4871038	Regular expression to get the value from []	string res = null;\nMatch m = Regex.Match(input, @"^=\[(.+)\].+$");\n\nif (m.Success)\n{\n    res = m.Groups[1].Value;\n}	0
1281257	1281236	Delete User from Table and ASPNET Membership Provider with sqlDataSource	void GridView1_RowDeleting(object sender, GridViewDeleteEventArgs e)\n{\n  string name = e.Values["IntranetUserName"] as string;\n}	0
33804360	33801709	EntityFramework: How to map a Zero-to-One relationship?	public virtual Allocation Allocation { get; set; }	0
16847202	16847064	Moving array segment within array	// T[] source\n// int dest\n// int start, end\nT[] slice = new T[end - start];\nArray.Copy(source, start, slice, 0, slice.Length);\n\nif (dest < start)\n{\n    // push towards end\n    Array.Copy(source, dest, source, dest + slice.Length, start - dest);\n}\nelse\n{\n    // push towards start\n    // who moves where? Assumes dest..dest+count goes left\n    Array.Copy(source, end, source, dest, dest - start);\n}\n\nArray.Copy(slice, 0, source, dest, slice.Length);	0
21705311	21703847	how to display result of a ?script table as create to query? with length of data type in a textbox?	case when st.Name in ('varchar','varchar','char','nchar')	0
20144390	20144206	How to update the value of a Label in footer template of a gridview?	var objGrid= document.getElementById('<%=YourGrid.ClientID%>');\nvar cells = objGrid.getElementsByClassName('footerClass') \n\ncells[0].innerText = ClsSum;\ncells[1].innerText = NonSaleSum;\ncells[2].innerText = SecSum;	0
2938275	2933776	Is there a way that I can register an event, on a control that inherits from Canvas, that is fired whenever any of it's children change in size?	public class MyCanvas : Canvas\n{\n    public event EventHandler ChildDesiredSizeChanged;\n    protected override void OnChildDesiredSizeChanged(UIElement child)\n    {\n        if (ChildDesiredSizeChanged != null) ChildDesiredSizeChanged(child, EventArgs.Empty);\n        base.OnChildDesiredSizeChanged(child);\n    }\n}	0
12330194	12330175	Show images - Screen is stuck	Freeze()	0
21049848	21049673	How do I create a color picker?	private void btnColour_Click(object sender, EventArgs e)\n{\n    ColorDialog clrDialog = new ColorDialog();\n\n    //show the colour dialog and check that user clicked ok\n    if (clrDialog.ShowDialog() == DialogResult.OK)\n    {\n        //save the colour that the user chose\n        c = clrDialog.Color;\n    }\n}\n\nColor c = Color.Black;	0
6920303	6891900	How to get the type of deserialized C# object from JSON text?	JObject json = JObject.Parse(JasonText);\n   var  type=   json["type"];	0
21830814	21828908	Sending sms from Windows Phone 7 application	smsComposeTask.Body = title.Text + "," + description.Text + "," + datee.Text;	0
323377	323342	Sorting the result of a stored procedure	myTable.DefaultView.Sort = "myColumn DESC";	0
6581669	6581426	polymorphic association and splitting tables	public abstract class Person\n{\n    public string FirstName { get; set; }\n    public string Surname { get; set; }\n}\n\npublic partial class Teacher : Person\n{   \n    public string School { get; set; }\n}\n\npublic partial class Student : Person\n{\n    public string YearLevel { get; set; }\n}\n\npublic partial class Parent : Person\n{\n    public string Blagh { get; set; }\n}	0
5935873	5935798	Custom object with nested collection	List<MeterPrevReadInfo> list = ...;\n\n var result = from item in list\n              from info in item.Regs\n              select new {item.DateMeterRead, info.MeterRead};	0
23214662	23214518	How to detect new posts	foreach (var item in data)\n  {\n      var post = (IDictionary<string, object>)item;\n\n      if (post["id"].ToString() == latestPostId)\n      {\n           end = true;\n           break;                               \n      }\n\n      //App logic continues...\n\n  }	0
18318420	18318352	c# how can I make a windows form non movable and movable again	private bool _preventMove = false;\n\nprotected override void WndProc(ref Message message)\n{\n    const int WM_SYSCOMMAND = 0??0112;\n    const int SC_MOVE = 0xF010;\n\n    if(_preventMove) \n    {\n        switch(message.Msg)\n        {\n            case WM_SYSCOMMAND:\n               int command = message.WParam.ToInt32() & 0xfff0;\n               if (command == SC_MOVE)\n                  return;\n               break;\n        }\n    }\n\n    base.WndProc(ref message);\n}	0
5197129	5197078	Attribute's default value = Name of the field possessing the attribute	public class WSField : Attribute {\n  // ...\n  internal string xmlField;\n  public WSField(string tableField, string xmlField = null) {\n\n...\n\npublic class FieldDefinition {\n  public FieldDefinition(FieldInfo fieldInfo) {\n    // ...\n    if (this.wsField.xmlField == null) this.wsField.xmlField = fieldInfo.Name;\n  }\n\n...	0
8339693	8339606	How to execute commands? via singleton utility method or via OnPropertyChanged?	EditingCommands.AlignLeft	0
17968330	17942443	Sql connetion doesn't open in windows service	ex: _connectionString = @"Data Source =.......";	0
10257907	10121616	How can I access Documents folder of iOS App with C#	MobileDevice.AMDeviceStartHouseArrestService(iPhoneHandle,      \nMobileDevice.CFStringMakeConstantString(bundleIdentifier), null, ref hService, 0);	0
2635928	2635868	finding all permutation of words in a sentence	public static List<string> PermuteWords(string s)\n    {\n        string[] ss = s.Split(new string[] {" "}, StringSplitOptions.RemoveEmptyEntries);\n        bool[] used = new bool[ss.Length];\n        string res = "";\n        List<string> list = new List<string>();\n        permute(ss, used, res, 0, list);\n        return list;\n    }\n\n    private static void permute(string[] ss, bool[] used, string res, int level, List<string> list)\n    {\n        if (level == ss.Length && res != "")\n        {\n            list.Add(res);\n            return;\n        }\n        for (int i = 0; i < ss.Length; i++)\n        {\n            if (used[i]) continue;\n            used[i] = true;\n            permute(ss, used, res + " " + ss[i], level + 1, list);\n            used[i] = false;\n        }\n    }	0
4699661	4699653	C# How to place a comma after each word but the last in the list	var index = 0;\nforeach (object itemChecked in RolesCheckedListBox.CheckedItems)\n{\n    if ( index>0 ) sw.Write( "," );\n    sw.Write(itemChecked.ToString());\n    index++;\n}	0
10604008	10603790	converting C# to C++ with Marshal problems	//Get size number of characters of the string pointed to by the positionMemory pointer.\nstring result = Marshal.PtrToStringAnsi(new IntPtr(positionMemory), size); \n\n//Copy the contents of objectStruct to the memory location pointed at by positionMemory\nMarshal.StructureToPtr(objectStruct, new IntPtr(positionMemory), true);\n\n//Copy size number of bytes from the byteName array starting at index 0 to the memory indicated by positionMemory\nMarshal.Copy(byteName, 0, new IntPtr(positionMemory), size);\n\n//I think offsetting the memory location indicated by allocatedObject by size number of bytes and converting the memory pointer to an Int64.\nmachineNamePosInMem = allocatedObject.Offset(size).ToInt64();	0
27135305	27131825	How can I keep a row highlighted even when i select another row. C# datagridview	List<DataGridViewRow> selectedRows = new List<DataGridViewRow>();\n\nvoid selectRows()\n{\n    dataGridView1.SuspendLayout();\n    foreach (DataGridViewRow r in dataGridView1.Rows) \n             r.Selected = selectedRows.Contains(r);\n    dataGridView1.ResumeLayout();\n}\n\nprivate void dataGridView1_MouseClick(object sender, MouseEventArgs e)\n{\n    DataGridViewRow clickedRow = dataGridView1.CurrentRow;\n\n    if (selectedRows.Contains(clickedRow))\n        selectedRows.Remove(clickedRow);\n    else\n        selectedRows.Add(clickedRow);\n\n    selectRows();\n}	0
11902827	11902510	Using Math.Ceiling with ints in C#	int chunkSize = 524288;  // 512kb\nint fileByteCount = GetFileSizeInBytes();\nint packetCount = (fileByteCount + chunkSize - 1) / chunkSize;	0
9199059	8962088	NHibernate - using properties from set in subselect	from Country a \nwhere (\n  select PropertyValue \n  from LocalizedProperty x \n  where x.Entity.id = a.Id \n    and x.PropertyName = 'Name' \n    and x.Entity.class = 'Prayon.Entities.Country' \n    and x.CultureName = 'de' take 1) \n  Like :val	0
16198931	16184928	Tab in Image with hotspots	protected override bool ProcessDialogKey(Keys keyData)\n        {\n            int selectionIndex = pBoundsCollection.IndexOf(pSelection);\n            if (keyData == Keys.Tab)\n            {\n                while (selectionIndex++ <= pBoundsCollection.Count)\n                {\n                    if (selectionIndex >= pBoundsCollection.Count)\n                    {\n                        selectionIndex = 0;\n                        pSelection = (CMRField)pBoundsCollection[selectionIndex];\n                        Refresh();\n                        break;\n                    }\n                    if (((CMRField)pBoundsCollection[selectionIndex]).IsSelectable)\n                    {\n                        pSelection = (CMRField)pBoundsCollection[selectionIndex];\n                        Refresh();\n                        return false;\n                    }\n                }\n            }\n            return base.ProcessDialogKey(keyData);\n        }	0
11529666	11526974	Date conversion: From LINQ to JSON to Javascript	function parseDate(date){\n    var year = parseInt(date.substring(0,4));\n    var month = parseInt(date.substring(5,7));\n    var day = parseInt(date.substring(8,10));\n    var hour = parseInt(date.substring(11,13));\n    var minute = parseInt(date.substring(14,16));\n    var second = parseInt(date.substring(17,19));\n    return new Date(year, month, day, hour, minute, second);\n}\n\nfor(i = 0; i < points.length; i++){\n    var date = Date.parse(points[i].EarnedOn);\n    ...	0
18099907	18099477	ASP.NET C# - using dataset to read one row?	using (SqlConnection con = new SqlConnection(connectionString))\n{\n\n    con.Open();\n\n    SqlCommand cmd = new SqlCommand("SELECT userid,username,email,city FROM USERS where username=@username and password=@password", con);\n    cmd.Paramters.AddWithValue("@username", username);\n    cmd.Parameters.AddWithValue("@password", password);\n    cmd.CommandType = CommandType.Text;\n\n    UserInfo info = new UserInfo();\n\n    using (SqlDataReader rdr = cmd.ExecuteReader())\n    {\n\n        if (rdr.HasRows)\n        {\n            rdr.Read(); // get the first row\n\n            info.UserID = rdr.GetInt32(0);\n            info.UserName = rdr.GetString(1);\n            info.Email = rdr.GetString(2);\n            info.City = rdr.GetString(3);\n        }\n    }\n}	0
3488734	3488729	Get DateTime from SQL database	company_reader2 = search_company2.ExecuteReader();\nif (company_reader2 != null && company_reader2.HasRows) {\n    company_reader2.Read();\n    dateform.Text = company_reader2[0].ToString();\n}	0
30447659	30447532	Serial Port Reading into TextBox	myPort.DataReceived += myPort_DataReceived;	0
5222133	5221949	Entity Framework 4 custom Data type	namespace TheNamespace\n{\n\n  public partial class TheEntity\n  {\n      public DateTime DateAdded \n      {\n         get {  }\n         set {  }\n      }\n  }\n}	0
9727683	9541284	How to include UserID and Password in the http header?	request.Headers.Add("UserID", userID);            \n               request.Headers.Add("Password", password);	0
15710776	15710609	Excel Interop's set_value method damages values	if (sheet.get_FilterMode()) {\n    sheet.ShowAllData();\n}	0
12569196	12569139	How to get which Type of parent object to reference the current object via property	public class C\n{\n    private readonly object _parent;\n    public C(object parent)\n    {\n        _parent;\n    }\n\n    public void Do()\n    {\n        Type type = _parent != null ? _parent.GetType() : null;\n        // Do something with type...\n    }\n}	0
12364468	12363807	Call webservice in windows application	System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()	0
783632	783597	Gridview with FileUpload control	protected void gridView_RowUpdating(object sender, GridViewUpdateEventArgs e)\n{\n    GridViewRow row = gridView.Rows[e.RowIndex];\n    FileUpload fileUpload = row.Cells[0].FindControl("fileUpload1") as FileUpload;\n    if (fileUpload != null && fileUpload.HasFile)\n    {\n        fileUpload.SaveAs(Server.MapPath("images/hardware/" + fileUpload.FileName));\n    }\n}	0
3497810	3497795	Trouble getting a list of a custom class to serialize for user.config	List<Column> ListOfColumns { get; set;}	0
8945563	8945404	string letters validation	Regex reg = new Regex("^[A-Za-z]+$");\n        do\n        {\n            DisplayDivider("Get Name");\n            strInput = GetInput("your Name");\n            isValid = reg.IsMatch(strInput);\n            if (!isValid)\n            {\n                isValid = false;\n                Console.WriteLine("'" + strInput + "' is not a valid name entry. Please retry...");\n            }\n        } while (!isValid);	0
20245677	20245553	website using iTextSharp needs to save PDF on local machine C drive	public FileResult GetFile()\n{\n    byte[] filebytes;\n\n    //load file data however you please\n    return File(filebytes, "application/pdf");\n}	0
18399066	18398690	How should I parse Infinity with Double?	Decimal.Parse("Infinity", System.Globalization.CultureInfo.InvariantCulture);	0
15011392	15011340	how do I move a panel with directional keyboard	private void lblMove_KeyUp(object server, KeyEventArgs e)\n    {\n          Point location = button1.Location;\n          switch(e.KeyCode)\n          {\n            case Keys.Up: \n                location.Y = location.Y -1;\n                break;\n            case Keys.Down:\n                location.Y = location.Y + 1;\n                break;\n            case Keys.Right:\n                location.X = location.X + 1;\n                break;\n            case Keys.Left:\n                location.X = location.X - 1;\n                break;\n          }\n\n          button1.Location = location;\n    }	0
13082691	13082514	Undo/redo in a graphics application	List<Action<Graphics>> actions = new List<Action<Graphics>>();\n\nactions.Add(gr => gr.Drawrectangle(pen, p1, p2));\nactions.Add(gr => gr.FillEllipse(brush, p, x, y));	0
7745165	7745015	How can I get a complex LINQ query to work where I need to check by two elements and an attribute?	string username = root.Elements("Username")\n                      .First(el => (string)el.Attribute("type") == type)\n                      .Element("Login")\n                      .Value;	0
15405118	15403898	Color detection by using C#	Bitmap.GetPixel()	0
8843366	8838909	ExpandableListView Mono for Android, ClickEvents	public class MyListener : Java.Lang.Object, ExpandableListView.IOnChildClickListener\n{\n    public override bool OnChildClick (ExpandableListView parent, View v, int groupPosition, int childPosition, long id)\n    {\n        return base.OnChildClick (parent, v, groupPosition, childPosition, id);\n    }\n}	0
26234531	26234089	How to catch console close event in PowerShell?	Register-EngineEvent PowerShell.Exiting -Action { "Exiting $(Get-Date)" >> C:\TEMP\log.txt }	0
4669370	4669317	How to convert a bitmap image to black and white in c#?	public Bitmap GrayScale(Bitmap Bmp)\n{\n    int rgb;\n    Color c;\n\n    for (int y = 0; y < Bmp.Height; y++)\n    for (int x = 0; x < Bmp.Width; x++)\n    {\n        c = Bmp.GetPixel(x, y);\n        rgb = (int)((c.R + c.G + c.B) / 3);\n        Bmp.SetPixel(x, y, Color.FromArgb(rgb, rgb, rgb));\n    }\n    return Bmp;\n}	0
15346122	15346088	substitute the number after decimal with 0	var num = 166.7;\nvar numString = (num * 100).ToString("000000000000");	0
4549045	4548786	BackgroundWorker + WebBrowser	private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {\n        if (e.Error != null) MessageBox.Show(e.Error.ToString());\n    }	0
21740391	21739538	Issues with loading winform for notification	private void btnSubmit_Click(object sender, EventArgs e)\n{\n    DisplayCustomMessageBox("Please Wait");\n\n    Thread t = new Thread(()=>\n    {\n        ProcessRequest();\n        this.BeginInvoke(new Eventhandler((s,ee)=>{\n            HideCustomMessageBox();\n        }));\n    });\n    t.Start();\n}	0
303752	303555	Using an interface to convert an object from one type to another?	var props = typeof(Foo)\n            .GetProperties(BindingFlags.Public | BindingFlags.Instance);\n\nforeach (PropertyInfo p in props)\n{\n     // p.Name gives name of property\n}	0
25219896	25219654	c# print right to left	e.Graphics.DrawString(dataToPrint, valueFont, \n        System.Drawing.Brushes.Black, 200, 20, format);	0
6153137	6153120	Concise way to initialise a collection	List<string> strList = new List<string>{ "foo", "bar" };\n\nList<Person> people = new List<Person>{\n                                new Person { Name = "Pete", Age = 12},\n                                new Person { Name = "Jim", Age = 15}\n                      };	0
12294707	12294653	Open a text file in C#	Process.Start("Yourfile.txt")	0
24035330	24033378	null from C# getting converted into 'NULL' in Sql Server	String Residence = xmlDoc.Descendants("Appointment").Single().Element("StateOfResidence");\nif(Residence == "NULL")\n{\n    Residence = null;\n}	0
13763293	13763239	How can I get the coordinates of a location on the grid?	y = (myNumber - 1) / 6 + 1;\nx = (myNumber - 1) % 6 + 1;	0
19313669	19312530	Retrieving Data Depending on the Username	public ActionResult Edit(int id)\n{\n    // Get the currently logged in user.\n    string userName = User.Identity.Name;\n    var user = db.Users.First(u => u.UserName == userName);\n\n    // Determine whether the requested id is the same id as the currently logged in user.\n    icerik icerik = db.icerik.Find(id);\n    if (icerik.Userid.HasValue && icerik.Userid.Value == user.UserId)\n    {       \n        ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);\n\n        // You should not need this SelectList anymore.\n        //ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);\n        return View(icerik);\n    }\n    // This redirect the unauthorized user to the homepage. This can be any other page of course.\n    return RedirectToAction("Index", "Home"); \n}	0
440129	439253	How do I call an AuthenticationService from a login control?	proteted void login_Authenticate(object sender, AuthenticateEventArgse){\n   AuthenticationServiceClient client = new AuthenticationServiceClient();\n   e.Authenticated = client.Login(login.UserName, login.Password, "", true);\n}	0
13254815	13254642	Exporting xls file from C# - doesn't save special letters	protected void btnDownloadList_Click(object sender, EventArgs e)\n{\n    ExcelExport = "<table><tr><td>Name</td><td>Surname</td><td>Telephone</td><td>E-mail</td></tr><tr><td> </td><td> </td><td> </td><td> </td></tr>" + StringExport + "</table>";\n\n    Response.AddHeader("Content-disposition", "attachment; filename=raport.xls");\n    Response.ContentType = "application/ms-excel";\n    byte[] BOM = { 0xEF, 0xBB, 0xBF }; // The BOM for UTF-8 encoding.\n    Response.BinaryWrite(BOM);\n    Response.Write(ExcelExport);\n    Response.End();\n\n}	0
8716111	8715712	cast jsondata from Ext.data.Store to list object	System.Web.HttpUtility.UrlDecode	0
22930936	22930821	Inserting a date to SQLite	string sqlFormattedDate = myDateTime.ToString("yyyy-MM-dd HH:mm:ss");	0
3227598	3227548	How to access ASP.NET ListView header programmatically?	var gridView = listView.View as GridView;\ngridView.Columns[0].Header = "MyCustomHeader"; //setting header to the first column	0
29679028	29678507	Read csv file c# with comma separator	using System;\nusing Microsoft.VisualBasic.FileIO;\n\nclass Program\n{\n    static void Main()\n    {\n    using (TextFieldParser parser = new TextFieldParser("C:\\csv.txt"))\n    {\n        parser.Delimiters = new string[] { "," };\n        while (true)\n        {\n        string[] parts = parser.ReadFields();\n        if (parts == null)\n        {\n            break;\n        }\n        Console.WriteLine("{0} field(s)", parts.Length);\n        }\n    }\n    }\n}	0
12555572	12555449	MYSQL Database Connection to ASPX website using C#	using MySql.Data.MysqlClient;\n\nnamespace OwnNameSpace\n{\n  public class Database\n  {\n    MySqlConnection connect;\n    string connection = "Data Source=localhost;Database=ASP;User ID=(your ID)";\n//constructor\npublic Database()\n{\n}\n\n  // this if want to select something in your db\n  public MySqlDataReader Select(string query)\n  {\n\n      connect = new MySqlConnection(connection);\n      connect.Close();\n      MySqlCommand command = connect.CreateCommand();\n      command.CommandText = query;\n      connect.Open();\n      MySqlDataReader reader;\n      return reader = command.ExecuteReader();\n  }\n\n  // this if want to insert/delete or update \n  public Boolean Modify(string query)\n  {\n\n      connect = new MySqlConnection(connection);\n      MySqlCommand command = connect.CreateCommand();\n      command.CommandText = query;\n      connect.Open();\n      try\n      {\n         command.ExecuteNonQuery();\n         return true;\n      }\n      catch\n      {\n        return false;\n      }\n\n   }\n\n\n\n }\n}	0
1652887	1647698	Using LINQ to Objects to find items in one collection that do not match another	employees.Except(employees.Join(managers, e => e.Id, m => m.EmployeeId, (e, m) => e));	0
4385850	4385651	How to auto generate Decorator pattern in C#	public class DecoratorProxy<T> : RealProxy\n{\n    private T m_instance;\n\n    public static T CreateDecorator<T>(T instance)\n    {\n        var proxy = new DecoratorProxy<T>(instance);\n        (T)proxy.GetTransparentProxy();\n    }\n\n    private DecoratorProxy(T instance) : base(typeof(T))\n    {\n        m_instance = instance;\n\n    }\n    public override IMessage Invoke(IMessage msg)\n    {\n        IMethodCallMessage methodMessage = msg as IMethodCallMessage;\n        if (methodMessage != null)\n        {\n            // log method information\n\n            //call method\n            methodMessage.MethodBase.Invoke(m_instance, methodMessage.Args);\n            return new ReturnMessage(retval, etc,etc);\n\n        }\n\n    }\n}	0
18167574	18165440	Add value in datagrid cell after value of combobox is selected c#	//EditingControlShowing event handler for your dataGridView1\nprivate void dataGridView1_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e){\n   ComboBox combo = e.Control as ComboBox;\n   if(combo != null) combo.SelectedIndexChanged += GridComboSelectedIndexChanged;\n}\nprivate void GridComboSelectedIndexChanged(object sender, EventArgs e) {\n   ComboBox combo = sender as ComboBox;\n   //Your populating code here\n   //you can access the selected index via combo.SelectedIndex\n   //you can access the current row by dataGridView1.CurrentCell.OwningRow\n   //then you can access to the cell 4 and cell 5 by dataGridView.CurrentCell.OwningRow.Cells[4] and dataGridView.CurrentCell.OwningRow.Cells[5]\n}	0
16649375	16649023	How to seek to a position in milliseconds using XAudio2	var offset = (int)Math.Floor(buffer.WaveFormat.SampleRate * barDuration / 128) * 128 * bar;	0
7573163	7563878	Data contract serialization for IList<T>	public static void Serialize<T>(this IList<T> list, string fileName)  \n{\n   try\n   {\n      var ds = new DataContractSerializer(list.GetType());\n      using (Stream s = File.Create(fileName))\n        ds.WriteObject(s, list);  \n   }\n   catch (Exception e)\n   {\n     _logger.Error(e);\n     throw;\n   } \n}	0
18815548	18815499	Convert string to smalldatetime before a database insert	if (ArrivalDate != DBNull.Value)\n                param[2].Value = Convert.ToDateTime(ArrivalDate);\n            else\n            {\n                param[2].Value = // default value\n            }	0
3231096	3231076	return a list of string as JSONResult	return Json(parts, JsonRequestBehavior.AllowGet);	0
5569658	5569657	Identify triangle points around a point	// assuming xA, yA, xB, yB, arrWidth, arrHeight are initialised\nvar xV = xB - xA;\nvar yV = yB - yA;\nvar v = Math.Sqrt(xV*xV + yV*yV);\nvar pArr1 = new[] {\n    xA + xV / 2 - xV * arrHeight / (2 * v) - yV * arrWidth / (2 * v),\n    yA + yV / 2 - yV * arrHeight / (2 * v) + xV * arrWidth / (2 * v) };\nvar pArr2 = new[] {\n    xA + xV / 2 - xV * arrHeight / (2 * v) + yV * arrWidth / (2 * v),\n    yA + yV / 2 - yV * arrHeight / (2 * v) - xV * arrWidth / (2 * v) };\nvar pArr3 = new[] {\n    xA + xV / 2 + xV * arrHeight / (2 * v),\n    yA + yV / 2 + yV * arrHeight / (2 * v) };	0
32842191	32742300	How to lose focus on DataGrid when clicking on another DataGrid?	public override void OnApplyTemplate()\n{\n  base.OnApplyTemplate();\n\n  dataGrid = GetTemplateChild("dataGrid") as DataGrid;\n  dataGrid.MouseUp += new MouseButtonEventHandler(dataGrid_MouseUp);\n  docGrid = GetTemplateChild("docGrid") as DataGrid;\n  docGrid.MouseUp += new MouseButtonEventHandler(docGrid_MouseUp);\n}\n\npublic void dataGrid_MouseUp(object sender, MouseEventArgs e)\n{\n  docGrid.UnselectAll();\n}\n\npublic void docGrid_MouseUp(object sender, MouseEventArgs e)\n{\n  dataGrid.UnselectAll();\n}	0
26270974	26270925	Print single JSON Object as a CSV in C#	string result = string.Empty;\n\nforeach (var item in jobj)\n{\n    if (!string.IsNullOrEmpty(result))\n    {\n        result += ",";\n    }\n    result += item.Key;\n}\nConsole.WriteLine(result);	0
27916459	27916339	Time in hh:mmXM format	DateTime.Now.ToString("hh:mmtt");	0
24760205	24759951	Is it possible create a new instance of a generic type inside the body of a generic method?	public interface ITest\n{\n    void DoSomething();\n}\n\npublic void GetData<T, U>(T varA, int acao) where U: ITest, new()\n{\n    var item = new U();\n    item.DoSomething();\n}	0
33062927	33062674	Overcoming a discrepancy in a division	decimal balance = 13m;\nint months = 3;\nint monthsRemaining = 3;\n\nfor (var i = 0; i < months; i++)\n{\n    decimal thisMonth = Math.Round(balance / monthsRemaining, 2);\n\n    balance -= thisMonth;\n    monthsRemaining -= 1;\n\n    Console.WriteLine("Month {0}: {1}", i + 1, thisMonth);\n}	0
6520361	6520007	ado.net number of rows that may be return by an sql select store procedure	int count = 0;\nusing (var dr = new SqlDataReader(cmd)) {\n   while (dr.Read()) count++;\n}	0
7832622	7832105	LINQ with Multiple GroupJoin	using (Model m = new Model())\n{\n    var result = from attack in m.Attacks\n                 group attack by attack.Player into attacksForPlayer\n                 select new\n                 {\n                     PlayerName = attacksForPlayer.Key.Name,\n                     NumberOfAttacks = attacksForPlayer.Count(),\n                     NumberOfKills = (from k in m.Kills\n                                      where attacksForPlayer.Contains(k.Attack)\n                                      select k).Count()\n                 };\n\n    // The result can be read like this:\n    foreach (var r in result)\n    {\n        // r.PlayerName, r.NumberOfAttacks, r.NumberOfKills\n    }\n}	0
30523090	30519785	Numbers Recognition in Microsoft Speech Recognition	int result = 0;\nint final_result = 0;\nfor (String word : words) {\n     if (word == "one") {\n         result = 1;\n     }\n     if (word == "two") {\n         result = 2;\n     }    \n     if (word == "twelve") {\n         result = 12;\n     }    \n     if (word == "thousand") {\n         // Get what we accumulated before and add with thousands\n         final_result = final_result + result * 1000;\n     }    \n}\nfinal_result = final_result + result;	0
12103406	12103197	Find a range inside a range using LINQ	var rangeStart = new DateTime(2012, 1, 1);\nvar rangeEnd = new DateTime(2012, 12, 31);\nvar res = list\n    .Where(item => (item.StartTime < rangeStart ? rangeStart : item.StartTime) < (item.EndTime < rangeEnd ? item.EndTime : rangeEnd) )\n    .ToList();	0
18602165	18602093	Regex pattern for text between 2 strings	string patternstart = Regex.Escape("Session[");\nstring patternend = Regex.Escape("]");\nstring regexexpr = patternstart + @"(.*?)" + patternend;	0
3572862	3572803	How can i open a file such that its length should be multiple of 94	if(new FileInfo(path).Length % 94 == 0)\n{\n   using(var reader = new StreamReader(path))\n   {\n       ...\n   }\n}\nelse \n    throw new ArgumentException("File-length not multiple of 94", "path");	0
2397448	2397280	Suppressing PostSharp Multicast with Attribute	private IEnumerable<PropertyInfo> SelectProperties( Type type )\n    {\n        const BindingFlags bindingFlags = BindingFlags.Instance | \n            BindingFlags.DeclaredOnly\n                                          | BindingFlags.Public;\n\n        return from property\n                   in type.GetProperties( bindingFlags )\n               where property.CanWrite &&\n                     !property.IsDefined(typeof(SuppressNotify))\n               select property;\n    }\n\n    [OnLocationSetValueAdvice, MethodPointcut( "SelectProperties" )]\n    public void OnSetValue( LocationInterceptionArgs args )\n    {\n        if ( args.Value != args.GetCurrentValue() )\n        {\n            args.ProceedSetValue();\n\n           this.OnPropertyChangedMethod.Invoke(null);\n        }\n    }	0
28069436	28068051	Check the size of an array inside a list and show each entity in the array as a unique list value	var result = accounts.OrderBy(x => x.Id)\n              .Select(x => new \n                {\n                   AccountNumber = x.AccountNumber,\n                   Balance = x.Balance,\n                   BillToCompanyName = x.BillToContact.CompanyName,\n                   BillToName = x.BillToContact.Name,\n                   PhoneNumbersCount = x.BillToContact.PhoneNumbers.Count(),  \n                                         //All phone numbers count including null\n                   PhoneNumbersList = x.BillToContact.PhoneNumbers\n                                       .Select(z => z.Number ?? String.Empty).ToList()\n                });	0
8578890	8578866	C# Replace group of numbers in a string with a single character	Regex r = new Regex(@"\d+", RegexOptions.None);\n            Console.WriteLine(r.Replace("Test123456.txt", "#"));\n            Console.Read();	0
12813447	12336026	How to add RollingFlatFileTraceListenerData programmatically	using D = System.Diagnostics;\n\n...\n\nprotected void Application_Start()\n{\n   if (D.Trace.Listeners["MyTraceListener"] == null)\n   {\n      D.Trace.Listeners.Add(new MyTraceListener("") { Name = "MyTraceListener" });\n   }\n\n   ...\n\n}	0
11611858	11611764	Randomly arrange a list<object>	var rnd = new Random();\nvar shuffledList = list.OrderBy(x => rnd.Next()).ToList();	0
20757404	20755950	How to access a resource file that's not in the root of the Resources folder? (Sharepoint 2010)	string resourceVal = SPUtility.GetLocalizedString("$Resources:ResourceKey",\n"Comp.Dept.Proj.Farm\\GlobalResources", language);	0
284078	284063	Using TryParse for Setting Object Property Values	public static Int32? ParseInt32(this string str) {\n    Int32 k;\n    if(Int32.TryParse(str, out k))\n        return k;\n    return null;\n}	0
33797516	33797029	How should I take an input, check against a dictionary, and if it matches replace with the definition?	var morseDictonary = new Dictionary<char, string>()\n{\n    { '.', ".-.-.-" },\n    { ',', "--..--" },\n    { ' ', " " },\n    { 'A', ".-" },\n    { 'B', "-..." },\n};\n\nvar example = "A , B .";\n\nvar result = String.Join("", example.Select(x => morseDictonary[x]));	0
4743095	4742085	Use XMLReader to access child nodes with duplicate names	XDocument xDoc = XDocument.Load(@"C:\Data.xml");\n    string amt = xDoc.Descendants("salesTaxAmt")\n                     .Elements("amt")\n                     .Single().Value;	0
31127720	31127676	Vacuum Sqlite database with EntityFramework 6.1	context.Database.ExecuteSqlCommand(TransactionalBehavior.DoNotEnsureTransaction, "VACUUM;");	0
11271238	11268873	How to get a string from ToolStripDropDownButton item clicked?	private void btn1_DropDownItemClicked(object sender, ToolStripItemClickedEventArgs e)\n{\n  MessageBox.Show(e.ClickedItem.Text); // ClickedItem = item clicked.\n}	0
18748533	18737670	EPiServer 7 GetChildren for a specific page. and list all under that page	PageReference listRoot = CurrentPage.PageLink;	0
30833614	28706377	Merging two different texture into one in unity3d	public Texture2D AddWatermark(Texture2D background, Texture2D watermark)\n{\n\n    int startX = 0;\n    int startY = background.height - watermark.height;\n\n    for (int x = startX; x < background.width; x++)\n    {\n\n        for (int y = startY; y < background.height; y++)\n        {\n            Color bgColor = background.GetPixel(x, y);\n            Color wmColor = watermark.GetPixel(x - startX, y - startY);\n\n            Color final_color = Color.Lerp(bgColor, wmColor, wmColor.a / 1.0f);\n\n            background.SetPixel(x, y, final_color);\n        }\n    }\n\n    background.Apply();\n    return background;\n}	0
5814287	5814254	How do I search for an existing value in a SQL Database?	insert into someTable (id, name)\nvalues newid(), 'some name'	0
4652317	4651843	Where to put data annotations tags?	public class IProductMetadata\n{         \n    [HiddenInput(DisplayValue = false)]\n    int ProductID;\n\n    [Required(ErrorMessage = "Please enter a product name")]         \n    string Name;\n\n    [Required(ErrorMessage = "Please enter a description")]         \n    string Description;\n    // etc\n}\n\n[MetadataType(typeof(IProductMetadata))]\npublic partial class Product\n{\n}	0
21998470	13729561	get GuiApplication of running Sap logon vb6 to c#	public static void testConnection()\n        {\n            SapROTWr.CSapROTWrapper sapROTWrapper = new SapROTWr.CSapROTWrapper();\n            object SapGuilRot = sapROTWrapper.GetROTEntry("SAPGUI");\n            object engine = SapGuilRot.GetType().InvokeMember("GetSCriptingEngine", System.Reflection.BindingFlags.InvokeMethod,\n                null, SapGuilRot, null);\n            SAPconnection.sapGuiApp = engine as GuiApplication;\n            GuiConnection connection = sapGuiApp.Connections.ElementAt(0) as GuiConnection;\n            GuiSession session = connection.Children.ElementAt(0) as GuiSession;\n            MessageBox.Show(session.Info.User + " !!||!! " + session.Info.Transaction);\n\n\n        }	0
14888046	14887878	How to send updates of item to database in DotNetNuke Module?	...\n//Before calling UpdateStudent, make sure your StudentId property is set\nstudent.StudentId = 123;\n....\n\npublic void UpdateStudent(Student student)\n{\n    using (IDataContext ctx = DataContext.Instance())\n    {\n        var rep = ctx.GetRepository<Student>();\n        rep.Update(student);\n    }\n}	0
14869289	14867235	How to show the Pop up from when click theASP calender date?	protected void cal_SelectionChanged(object sender, EventArgs e)\n    {\n\n        lblSelectDate.Text = cal.SelectedDate.ToString();\n    }	0
6891999	6891965	How to save current application state of classes using Winform?	var p=new Person();\np.FirstName = "Jeff";\np.MI = "A";\np.LastName = "Price";\nSystem.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());\nx.Serialize(Console.Out, p);	0
11272700	11272680	Insert data to a table - web service in visual studio	"INSERT into [User] values(@fname,@lname,@email,@num,@locID)"	0
22453035	22452932	How to trigger button click event on pressing enter button in c#	if (e.Key == Key.Enter)\n{\n  LoginButton_Click(sender,e); //here LoginButton_Click is click eventhandler\n}	0
4262362	4262339	Checking checkboxes with webbrowser element	javascript:document.getElementById('theCheckBox').setAttribute('checked', 'checked');document.getElementById('theForm').submit();	0
31244769	31244536	Sending a byte with .net UDP sockets in C#	byte[] send_buffer = { ((byte)MyEnum.Enum1) };	0
1104156	1104121	How to convert a DataTable to a string in C#?	Private Sub PrintTableOrView(ByVal table As DataTable, ByVal label As String)\n    Dim sw As System.IO.StringWriter\n    Dim output As String\n\n    Console.WriteLine(label)\n\n    ' Loop through each row in the table. '\n    For Each row As DataRow In table.Rows\n        sw = New System.IO.StringWriter\n        ' Loop through each column. '\n        For Each col As DataColumn In table.Columns\n            ' Output the value of each column's data.\n            sw.Write(row(col).ToString() & ", ")\n        Next\n        output = sw.ToString\n        ' Trim off the trailing ", ", so the output looks correct. '\n        If output.Length > 2 Then\n            output = output.Substring(0, output.Length - 2)\n        End If\n        ' Display the row in the console window. '\n        Console.WriteLine(output)\n    Next\n    Console.WriteLine()\nEnd Sub	0
1987214	1987193	DataGridView: How to select an entire Column and deselect everything else?	grid.ClearSelection();\nfor(int r = 0; r < grid.RowCount; r++)\n    grid[columnIndex, r].Selected = true;	0
3185352	3184957	How to get a distinct list of first letters with NHibernate	companies.Select(company => company.Name.Substring(0, 1));	0
26872372	26871079	What is the proper way to construct a Biginteger from an implied unsigned hexedicimal string in C#?	BigInteger.TryParse(string.Format("0{0}", "FFFF"), style, ...)	0
22603425	22603204	How to draw moving text with GDI+	g.TextRenderingHint = System.Drawing.Text.TextRenderingHint.SingleBitPerPixel;	0
22451757	22451688	Access ViewModel from Tablesource	public class TableSource : MvxSimpleTableViewSource\n    {\n        private TwitterView _parent;\n\n        public TableSource (UITableView tableView, TwitterView parent)\n            : base(tableView, TweetCell3.Identifier, TweetCell3.Identifier)\n        {\n            _parent = parent;\n            tableView.RegisterNibForCellReuse(UINib.FromName(TweetCell3.Identifier, NSBundle.MainBundle), TweetCell3.Identifier);\n        }\n\n        public override float GetHeightForRow (UITableView tableView, NSIndexPath indexPath)\n        {\n            return _parent.SomeMethod(indexPath);\n        }\n    }	0
16044841	16044671	Calculating 100 Miles Within a Radius	create function dbo.F_GREAT_CIRCLE_DISTANCE\n(\n    @Latitude1  float,\n    @Longitude1 float,\n    @Latitude2  float,\n    @Longitude2 float\n)\nreturns float as\nbegin\n    declare @radius float\n\n    declare @lon1  float\n    declare @lon2  float\n    declare @lat1  float\n    declare @lat2  float\n\n    declare @a float\n    declare @distance float\n\n    -- Sets average radius of Earth in Miles\n    set @radius = 3956\n\n    -- Convert degrees to radians\n    set @lon1 = radians( @Longitude1 )\n    set @lon2 = radians( @Longitude2 )\n    set @lat1 = radians( @Latitude1 )\n    set @lat2 = radians( @Latitude2 )\n\n    set @a = sqrt(square(sin((@lat2-@lat1)/2.0E)) + (cos(@lat1) * cos(@lat2) * square(sin((@lon2-@lon1)/2.0E))) )\n    set @distance = @radius * ( 2.0E *asin(case when 1.0E < @a then 1.0E else @a end ))\n\n    return @distance\nend	0
7517920	7517829	How can I write a web service that returns a dynamic set of variables in .NET?	List<KeyValuePair<string, object>>	0
26911669	26911211	ask : random string without repitition c#	List<string> femalePetNames = { "Maggie", "Penny", "Saya", "Princess", \n                            "Abby", "Laila", "Sadie", "Olivia", \n                            "Starlight", "Talla" };\n    public void StringRandom()\n    {\n        if (femalePetNames.Count > 0)\n        {\n            Random bsd = new Random();\n\n            int fIndex = bsd.Next(0, femalePetNames.Count);\n            txttBox2.Text = femalePetNames[fIndex];\n            femalePetNames.RemoveAt(fIndex);\n        }\n    }	0
34007667	34007507	Read In External File Then Display After Caesar Shift	public static void Main(string[] args)\n{\n    //Read in code to shift from text file.\n    var file = @"txt"; //I have a file linked here\n    var text = File.ReadAllText(file);\n    //Show original unshifted code. \n    Console.WriteLine("Original text reads: \n\n{0}", text);\n\n    //Show text after shift. \n    Console.WriteLine("The shifted code is: \n\n{0}", Caesar(text, 18));\n}	0
2941094	2939866	Issue with child of custom Decorator class in WPF	protected override Size ArrangeOverride(Size arrangeSize)\n{\n    base.ArrangeOverride(arrangeSize);\n    return arrangeSize;\n}	0
29658521	29549951	How do I apply a new group to a user in an OU in Microsoft Active Directory	private void AddMemberToGroup(string bindString, string newMember)\n{\n    try\n    {\n        DirectoryEntry ent = new DirectoryEntry(bindString);\n        ent.Properties["member"].Add(newMember);\n        ent.CommitChanges();\n    }\n    catch (Exception e)\n    {\n        // do error catching stuff here\n        return;\n    }\n}	0
18843459	18843344	Equivalent for nullable value check	Dim x? As Integer\nDim x As Integer?\nDim x As Nullable(Of Integer)\n\n\nDim s As Integer\n\ns = If(x, 5)	0
21301244	21300049	How to create text file based on date in c#	using System.Text.RegularExpressions;\n    using System.IO;\n    using System.Text;\n\n    string pattern = "^3/1/2014.*"; \n    string strPath = new string("c:\\"); \n    string strDateTime = DateTime.Now.ToString("yyyyMMdd"); \n    string FileToCopy = "c:\\regexTest.txt"; \n    string NewCopy = strPath + strDateTime + ".txt"; \n    StringBuilder sb = new StringBuilder(""); \n    if (System.IO.File.Exists(FileToCopy) == true) { \n    string[] lines = File.ReadAllLines(FileToCopy); \n    foreach (string line in lines) { \n    if (Regex.IsMatch(line, pattern)) { \n    sb.Append(line + System.Environment.NewLine); \n    } \n    } \n    } \n\n    if (sb.Length > 0) { \n    System.IO.File.WriteAllText(NewCopy, sb.ToString); \n    }	0
11143107	11142811	How to create delegate from lambda expression with parameters?	((Action<ViewModel>)d1)(yourparameter)	0
18370652	18120353	Assign custom object into Object type variable in SSIS	using System;\nusing System.Data;\nusing Microsoft.SqlServer.Dts.Runtime;\nusing System.Windows.Forms;\n\nnamespace ST_8eab6a8fbc79431c8c9eb80339c09d1d.csproj\n{\npublic class myclass\n{\n    int a, b;\n\n    public myclass()\n    {\n        a = 0;\n        b = 0;\n    }\n}\n\n[System.AddIn.AddIn("ScriptMain", Version = "1.0", Publisher = "", Description = "")]\npublic partial class ScriptMain : Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTARTScriptObjectModelBase\n{\n    #region VSTA generated code\n    enum ScriptResults\n    {\n        Success = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Success,\n        Failure = Microsoft.SqlServer.Dts.Runtime.DTSExecResult.Failure\n    };\n    #endregion\n\n    public void Main()\n    {\n        Dts.TaskResult = (int)ScriptResults.Success;\n        myclass m = new myclass();\n        Dts.Variables["myObject"].Value = m;\n    }\n}	0
6696275	6696236	Error when splitting string with string	PostBuffer.Split(new string[] { "----WebKitFormBoundaryBBZbLlWzO0CIcUa6"}, StringSplitOptions.None);	0
19613987	19544482	Scale MapOvleray in WindowsPhone8	public static double MetersToPixels(double meters, double latitude, double zoomLevel)\n    {\n        var pixels = meters / (156543.04 * Math.Cos(latitude) / (Math.Pow(2, zoomLevel)));\n        return Math.Abs(pixels);\n    }	0
22370516	22369216	How to make a return statement to open wpf windows in C#	if (txtUserName.Text == "admin" && txtPassword.Password.ToString() == "admin")	0
7113082	7110888	Databind Repeater based on value in column	protected void ddlViewLabel_SelectedIndexChanged(object sender, EventArgs e)\n{\nDropDownList d = (DropDownList)sender;\n\n// psudeo code from here on out\n// get the DropDownList selected index\n// create the new SQL statement\n// either create a new SQlDataSource or SqlCommand/SqlConnection objects, set the sql, attach them to the repeater, bind\n\n}	0
10356680	10356635	Displaying data in a grid	DataTable table = new DataTable("myTable");\nusing(OdbcConnection conn = new OdbcConnection("specfiy_conn_string"))\n{\n    using(OdbcDataAdapter da = new OdbcDataAdapter(@"SELECT * FROM MyTable", conn))\n        da.Fill(table);\n}\ndataGridView1.DataSource = table.DefaultView; //binding table to dgv	0
21027896	21027443	How to make Designer in Visual Studio generate component using parameterize constructor	class ClockComponent : Component {\n    public ClockComponent(IContainer container) { \n        // Add object to container's list so that \n        // we get notified when the container goes away container.Add(this); \n    } \n    // ...\n}	0
13873918	13873877	Disable textbox after typing in a value C#	TextBox.LostFocus	0
17721409	17531140	MsWord plugin with NetOffice automation - extracting image	IDataObject data = null;\n\n                Exception threadEx = null;\n                Thread staThread = new Thread(\n                    delegate()\n                    {\n                        try\n                        {\n                            data = Clipboard.GetDataObject();\n                            if (data.GetDataPresent(DataFormats.Bitmap))\n                            {\n                                Bitmap bmp = (System.Drawing.Bitmap)data.GetData(DataFormats.Bitmap);\n                                string filename = String.Format(@"c:\image{0}.bmp", i.ToString());\n                                bmp.Save(filename);\n                            }\n                        }\n\n                        catch (Exception ex)\n                        {\n                            threadEx = ex;\n                        }\n                    });\n                staThread.SetApartmentState(ApartmentState.STA);\n                staThread.Start();\n                staThread.Join();	0
18908167	18902767	How to convert richtext document inlines back to Label	List<UIElement> labels = new List<UIElement>();\n\nforeach (var block in myRTB.Document.Blocks)\n{\n    if (block is Paragraph)\n    {\n        var paragraph = block as Paragraph;\n        foreach (var inline in paragraph.Inlines)\n        {\n            if(inline is InlineUIContainer)\n            {\n    labels.Add(((InlineUIContainer)inline).Child);\n            }\n        }\n\n    }\n}	0
31826379	31826248	Method for Focus Change	foreach(Control ctrl in this.Controls)\n{\n   ctrl.Enter += new EventHandler(Focus_Changed); // Your method to fire\n}	0
25056862	25056474	Linq lambda arguments	Func<IEnumerable<XElement>, string, string, IEnumerable<XElement>> functionSearch;\nfunctionSearch = (l, x, y) => l.Where(m => m.Descendants(x).Any(v => v.Value.Contains(y)));	0
1911333	1427747	Create a G3 fax image with an ASN.1 wrapper for ldap photo	G3FacsimileBodyPart ::= SEQUENCE { parameters G3FacsimileParameters, \n                                   data       G3FacsimileData}\nG3FacsimileParameters ::= SET { number-of-pages [0] INTEGER OPTIONAL, \n                                non-basic-parameters [1] G3FacsimileNonBasicParameters  \n                                OPTIONAL}\nG3FacsimileData ::= SEQUENCE OF BIT STRING	0
8835804	8835786	Deploy XML file and load it	XDocument configXML = XDocument.Load("Config.xml");	0
32533701	32533599	sql server comparing numeric filed with a string that contains comma seprated numbers using IN command	DECLARE @tbl TABLE(ID INT, SomeValue VARCHAR(10));\nINSERT INTO @tbl VALUES\n (1,'value 1')\n,(2,'value 2')\n,(3,'value 3')\n,(4,'value 4')\n,(5,'value 5');\n\nDECLARE @ListOfIDs VARCHAR(20)='1,3,5';\n\nWITH ListOfIDs AS\n(\n    SELECT CAST('<root><r>'+REPLACE(@ListOfIDs,',','</r><r>')+'</r></root>' AS XML) AS IDsAsXML\n)\n,ListOfIDsResolved AS\n(\n    SELECT x.y.value('.','int') AS ID\n    FROM ListOfIDs\n    CROSS APPLY ListOfIDs.IDsAsXML.nodes('/root/r') x(y)\n)\nSELECT * FROM @tbl AS tbl\nINNER JOIN ListOfIDsResolved ON tbl.ID=ListOfIDsResolved.ID	0
15722047	15721967	How do I convert this VB.NET array expression to C#	if (new []{"red", "blue"}.Contains("blue")) return true;	0
14399395	14344825	What is the purpose of TaskCreationOptions with a TaskCompletionSource?	new TaskCompletionSource<WebResponse>(TaskCreationOptions.LongRunning);	0
3728918	3728585	how to recognize PDF format?	%PDF-1.X	0
7421132	7420043	how to get selected dataRow from combobox	DataRowView vrow = (DataRowView)cboItems.SelectedItem;\nDataRow row = vrow.Row;	0
1907163	1907099	WPF reading Style from ResourceDictionary to Control in C# code	myControl.Style =  (Style)res["ComboBoxTextBox"];	0
12108823	12108582	Extracting string between two characters?	string input = @"""abc"" <abc@gmail.com>; ""pqr"" <pqr@gmail.com>;";\nvar output = String.Join(";", Regex.Matches(input, @"\<(.+?)\>")\n                                    .Cast<Match>()\n                                    .Select(m => m.Groups[1].Value));	0
1564767	1564680	how to limit rows in dataGridView?	public DataTable CreateDataTable(bool headerRow)	0
21659179	21659022	How to read CSV file group by group	var lines = new List<string>(File.ReadLines("input.csv"));\nforeach (string line in lines)\n{\n    if (line.StartsWith("a")) continue;\n    // insert code to modify the other lines\n}\n// ... and later\nFile.WriteAllLines("output.csv", lines);	0
5440584	4917031	Writing a HtmlHelper 'Table' method, which uses the model DisplayName's	public static string GetDisplayName<T>( T toCheck )\n{\n  Type enumType = typeof(T);\n  if( !enumType.IsEnum ) return null;\n\n  MemberInfo[] members = enumType.GetMember(toCheck.ToString());\n\n  if( ( members == null ) || ( members.Length != 1 ) ) return toCheck.ToString();\n\n  foreach( MemberInfo memInfo in members )\n  {\n      DisplayAttribute[] attrs = (DisplayAttribute[]) memInfo.GetCustomAttributes(typeof(DisplayAttribute), false);\n\n      if( ( attrs != null ) && ( attrs.Length == 1 ) ) return attrs[0].Name;\n  }\n\n  return toCheck.ToString();\n}	0
22755353	22708719	Button onclick in DetailsView	protected void Button1_Click(object sender, EventArgs e)\n    {\n        //Get path from web.config file to upload\n        string FilePath = ConfigurationManager.AppSettings["FilePath"].ToString();\n        bool blSucces = false;\n        string filename = string.Empty;\n        string pathname = string.Empty;\n        string filePathName = string.Empty;\n\n        //To access the file upload control\n        //First get the clicked button\n        Button btn = (Button)sender;\n\n        //Then get the detailsview row\n        DetailsViewRow drv = (DetailsViewRow)btn.Parent.Parent;\n\n        //Now you can access the FileUpload control\n        FileUpload FileEditUpload1 = (FileUpload)drv.FindControl("FileEditUpload1");\n        if (FileEditUpload1.HasFile)\n        {\n            //Do the rest of your code\n        }\n    }	0
17342919	17342820	Combine values from two columns into the third column	DECLARE @TABLE TABLE(\n        AUTOID INT IDENTITY(1,1),\n        BRANCHID INT,\n        QUTNO AS CAST(BRANCHID AS VARCHAR(25)) + '#' + CAST(AUTOID AS VARCHAR(25))\n)\n\nINSERT INTO @TABLE (BRANCHID) VALUES (10),(11)\n\nSELECT * FROM @TABLE	0
9730344	9729823	Finding out number of dropdown lists	if (ddl.Items.Count <= 1) \n{\n    e.Cancel = true;\n}	0
23469210	23460423	How to get media:thumbnail from Youtube API in Windows Phone?	ImageSRC = entry.Element(media + "group").Element(media + "thumbnail").Attribute("url").Value	0
14990163	14989943	When dynamically adding controls to a form only one will show	Label tempLab = new Label();\ntempLab.Text = "Test Label";\ntempLab.AutoSize = true;\nControls.Add(tempLab);\ntempLab.Location = new Point(5,5);\n\nButton tempBut = new Button();\ntempBut.Text = "Test Button";\nControls.Add(tempBut);\ntempBut.Location = new Point(20,20);	0
13854739	13854147	authentication failed while connecting to tfs using tfs api	TfsTeamProjectCollection collection = new TfsTeamProjectCollection(\n    new Uri(http://server:8080/tfs/DefaultCollection,\n    new System.Net.NetworkCredential("domain_name\\user_name", "pwd"));\ncollection.EnsureAuthenticated();	0
26317073	24554464	NHibernate: How to reference the assembly of the main project from the unit test project?	Assembly.Load("Project Name of Desired Assembly")	0
1249519	1249506	Alternatives to decorator pattern	beverage2 = new Mocha(beverage2);                                       \nbeverage2 = new DarkRoast(beverage2);                                       \nbeverage2 = new Whip(beverage2);	0
7651068	7650915	Capturing Ctrl + Shift + P key stroke in a C# Windows Forms application	private void Form1_KeyDown(object sender, KeyEventArgs e)\n    {\n        if (e.Control && e.Shift && e.KeyCode == Keys.P)\n        {\n            MessageBox.Show("Hello");\n        }\n    }	0
28246831	28211137	Dynamically add a linked field to an ASP.NET MVC EF model	private List<Item> _linkedItems;\n\nprivate void UpdateLinksTo() {\n    this.LinksTo = string.Join<string>(_linkedItems.Select(i => i.ID.ToString()));\n}\n\n[NotMapped]\npublic ReadOnlyCollection<Item> LinkedItems {\n    get {\n        if(_linkedItems == null) {\n            _linkedItems = db.Items.Where(i => this.LinksTo.Split(',').Select(x => int.Parse(x)).Contains(i.ID)).ToList();\n        }\n        return _linkedItems.AsReadOnly();\n    }\n}\n\n[NotMapped]\npublic void AddLinkedItem(Item item) {\n    if(!_linkedItems.Select(i => i.ID).Contains(item.ID)) {\n        _linkedItems.Add(item);\n        UpdateLinksTo();\n    }\n}	0
5194223	5193381	Selecting sounds from Windows and playing them	private void Form1_Load(object sender, EventArgs e)\n    {\n\n        var systemSounds = new[]\n                              {\n                                  System.Media.SystemSounds.Asterisk,\n                                  System.Media.SystemSounds.Beep,\n                                  System.Media.SystemSounds.Exclamation,\n                                  System.Media.SystemSounds.Hand,\n                                  System.Media.SystemSounds.Question\n                              };\n\n        comboBox1.DataSource = systemSounds;\n\n        comboBox1.SelectedIndexChanged += new EventHandler(comboBox1_SelectedIndexChanged);\n    }\n\n    void comboBox1_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        ((System.Media.SystemSound)comboBox1.SelectedItem).Play();\n    }	0
34223566	34222529	How do I add a new region using roslyn (CodeFixProvider)	SyntaxFactory.RegionDirectiveTrivia()	0
18528168	18528091	Select NULL values from SQL Server table	mb.Mem_Email = reader["Mem_Email"] == System.DBNull.Value ? null : (string) reader["Mem_Email"];	0
21693093	21691653	Selecting specific textbox to focus for Windows Phone 8	// use this method to your 2 textbox\nprivate void yourTextBox_GotFocus(object sender, RoutedEventArgs e)\n{\n    (sender as TextBox).Text = string.Empty;\n}	0
5292645	5115655	Download file: truncated	Response.End()	0
4103959	4103943	How to create a RectangleF using two PointF?	new RectangleF(Math.Min(start.X, end.X),\n               Math.Min(start.Y, end.Y),\n               Math.Abs(start.X - end.X),\n               Math.Abs(start.Y - end.Y));	0
25920589	25920505	FormatException - Input string was not in a correct format	dr["Column"].ToString()	0
7053631	7053350	How to get name of type contained within missing assembly	Mono.Cecil	0
4106077	4105210	Freeze excel column with c#	worksheet.Activate();\n        worksheet.Application.ActiveWindow.SplitColumn = 1;\n        worksheet.Application.ActiveWindow.FreezePanes = true;	0
4228896	4228798	In Silverlight 4: how to set the Opacity of a Stroke programmatically?	tempStroke.DrawingAttributes.Color = Colors.FromArgb(125,255,0,0);	0
28602178	28405510	How to set focus on a TextBox when a form opens?	textbox1.select()	0
1049979	1049855	C# / Access Getting Primary Keys from Access 2003	GetSchema()	0
9497885	9497720	Select Query Not retrieving data from tables?	CREATE procedure SP_GetEmployeeRequests\n    (\n         @ApproverName varchar (50)\n    )\n    AS\n    BEGIN\n\n    SELECT ed.Emp_Username, rd.Request_Amount, rd.Request_description, bt.Balance_Amount, bt.LastApproval, bt.LastUpdated\n    FROM EmployeeDetails ed JOIN RequestDetails rd ON ed.Emp_ID = rd.emp_ID \n    JOIN BalanceTracker bt ON bt.Emp_ID = rd.Emp_ID\n    JOIN ApprovalDetails ad ON rd.Approved_ID  = ad.Approved_ID\n    WHERE ad.Approved_By = @ApproverName \n\n    END\n    GO	0
1136252	1136210	Am I implementing IDisposable correctly?	public virtual void Dispose()\n {\n\n     _Writer.Dispose();\n }	0
6363745	6363722	evaluate a string as a property in C#	Foo foo = new Foo();\nvar barValue = foo.GetType().GetProperty("Bar").GetValue(foo, null)	0
17380257	17380200	C# - String was not recognized as valid datetime	CultureInfo culture = new CultureInfo("en-US"); // or whatever culture you want\nConvert.ToDateTime(date, culture);	0
3166035	3166023	LINQ Group by with two statements	var r = from i in myList\n            group i by new { i.Number, i.CurrentStatus }\n                into grp\n                select new\n                {\n                    Reported = grp.Key.CurrentStatus,\n                    Number = grp.Key.Number,\n                    Sum = grp.Sum(x => x.Details[0].Quantity),\n                    Name = grp.Select(x => x.Name).First(),\n                    Details = grp.Select(x => x.Details).First(),\n                    Descriptions = grp.Select(x => x.Descriptions).First(),\n                    AssignmentId = grp.Select(x => x.AssignmentId).First(),\n                    Listor = grp.Select(x => x.Number).Count()\n                };	0
25186205	25186030	Windows Time Stamp format (type of MOUSEMOVEPOINT return value)	Environment.TickCount	0
19556063	19555892	Handling exceptions thrown in a canceled Task	task.ContinueWith(HandleError, TaskContinuationOptions.OnlyOnFaulted);	0
21713168	21713099	Convert Byte Array to string of numbers [c#]	Astr = new String(AByte.Select (b=>(Char)(b+ 48)).ToArray())	0
8648403	8639521	Retain string after being returned from multiple hooked events in C#	public delegate string IncomingMessageHook(int id);\n    public event IncomingMessageHook InComingMessage;\n    private string OnInComingMessage(int id)\n    {\n        IncomingMessageHook handler = null;\n        Delegate[] targets = null;\n        string result;\n\n        handler = InComingMessage;\n        if (handler != null)\n        {\n            targets = handler.GetInvocationList();\n            foreach (Delegate target in targets)\n            {\n                try\n                {\n                    handler = (IncomingMessageHook)target;\n                    result = handler.Invoke(id);\n                    if (!String.IsNullOrEmpty(result))\n                    {\n                        break;\n                    }\n                }\n                catch (Exception ex)\n                {\n                }\n            }\n        }\n        return result;\n   }	0
6718992	6718975	Cycle through a text file looking for a string, when matched return true	while(true) {\n    Thread.Sleep(500); // lets get a break\n    if(!System.IO.File.Exists(FILE_NAME)) continue;\n    using (System.IO.StreamReader sr = System.IO.File.OpenText(FILE_NAME)) \n    {\n        string s = "";\n        while ((s = sr.ReadLine()) != null) \n        {\n            if(s.Contains(TEXT_TO_SEARCH)) {\n                // output it\n            }\n        }\n    }\n}	0
31323468	31323349	How to add Pre render Event to a repeater control	foreach (RepeaterItem item in rptServices.Items)\n{\n    if (item.ItemType == ListItemType.Item || item.ItemType == ListItemType.AlternatingItem)\n    {\n       var textbox = (TextBox)item.FindControl("tbx");\n\n       //Do something with your textbox\n       textbox.Text = "Test";\n    }\n}	0
32671408	32670219	WPF WebBrowser Control loading local file readonly	File.Copy("path_to_pdf", Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString() + ".pdf");	0
20717381	20717254	How to filter out listviewitem{} string	String St = proxy.ToString();\nMessageBox.Show(St.Substring(0, St.LastIndexOf(':')).Substring(St.IndexOf('{') + 1));	0
28540090	28540079	How to put viewbag value as a variable in javascript/ jquery?	var ThematicId = parseInt('@ViewBag.thematicid');\nvar ThematicName =  '@ViewBag.Name';	0
29025190	29003905	How to play video using Youtube Data API v3 and video id in Windows Universal App	try\n    {//\n        var pathUri = await YouTube.GetVideoUriAsync("GC2qk2X3fKA", YouTubeQuality.Quality480P);\n        player.Source = pathUri.Uri;\n    }\n    catch (Exception ex)\n    {\n        if (ex is FormatException)\n        {\n            // handle exception. \n            // For example: Log error or notify user problem with file\n        }\n    }	0
3960216	3960128	paging in gridview	GridView1.PageIndex = 0;	0
12042587	12041453	Outlook Add on for Hyperlink recognition	String content = msg.Body;\ncontent = content.Replace("123456", "<a href=\"url\">123456</a>");\nmsg.Body = content;	0
28943488	28943487	How to get an IBuffer from an IRandomAccessStream	IRandomAccessStream stream = ...;\n\nusing (var memoryStream = new MemoryStream())\n{\n    memoryStream.Capacity = (int)stream.Size;\n    var ibuffer = memoryStream.GetWindowsRuntimeBuffer();\n    await stream.ReadAsync(ibuffer, (uint)stream.Size, InputStreamOptions.None).AsTask().ConfigureAwait(false);\n}	0
2878158	2878133	Delete the last instance of a certain string from a text file without changing the other instances of the string	var needle = "M6T1";\nvar ix = str.LastIndexOf(needle);\nstr = str.Substring(0, ix) + str.Substring(ix + needle.Length);	0
29096106	29095496	Insert picture into picturebox from a looped class?	pbxNy.Image = (Image)kortlek[i].bild	0
13640007	13639983	Deleting a Row from grid not working	if (Grid.Rows.Count > 1)\n        {\n            if (ViewState["CurrentTable"] != null)\n            {\n                DataTable dtCurrentTable = (DataTable)ViewState["CurrentTable"];\n                dtCurrentTable.Rows.RemoveAt(dtCurrentTable.Rows.Count -1);\n                ViewState["CurrentTable"] = dtCurrentTable;\n                Grid.DataSource = dtCurrentTable;\n                Grid.DataBind();\n\n            }\n            else\n            {\n                Response.Write("ViewState is null");\n            }\n        }	0
8143727	8143503	How do I return an empty string in a Null property when converted to JSON?	public class Customer\n{\n  public string GenderOrEmptyString {get {return this._gender ?? ""; }\n}	0
8259893	8259742	Asp.Net MVC3 Singleton variable	public class GlobalScope \n{\n  public String Variable { get; set; }\n}	0
23933877	23933580	asp.net web api - model binding list parameter	Web API only uses model binding for ???simple types???	0
12014076	11878654	WinRT - Loading data while keeping the UI responsive	SyndicationFeed feed = null;\n\nSyndicationClient client = new SyndicationClient();\n\nvar feedUri = new Uri(myUri);\n\ntry {\n    var task = client.RetrieveFeedAsync(feedUri).AsTask();\n\n    task.ContinueWith((x) => {\n        var result = x.Result;\n\n        Parallel.ForEach(result.Items, item => {\n            Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,\n            () =>\n            {\n                test.Text += item.Title.Text;\n            });\n       });     \n   });\n}\ncatch (Exception ex) { }	0
21280140	21280047	ListBox not displaying string (but bools) using databinding in WPF	public String description {get; set;}	0
16456971	16444021	SelectNodes with Filter	XmlNodeList nodeList0 = root.SelectNodes(@"//ns1:Department[(ns1:InstrumentData/@StatusCode='1'\n                                                                or ns1:InstrumentData/@StatusCode='2')\n                                                                 and not (ns1:InstrumentData/@RoleType='ED' \n                                                                    or ns1:InstrumentData/@RoleType='FD') \n                                                                and (ns1:InstrumentData/@Style='S' \n                                                                     or ns1:InstrumentData/@Style='T') ]", manager);	0
20749284	20749247	combining if conditions inside a lambda	return list.All(a => a.SomeId == 0 || IsAuthorizedOnID(TheUserID, a.SomeID));	0
410332	410324	Writing text to the middle of a file	open master file for reading.\ncount := 0\nwhile not EOF do\n    read line from master file into buffer\n    write line to output file    \n    count := count + 1\n    if count = 5 then\n       write added line to output file\n    fi\nod\nrename output file to replace input file	0
4586613	4586323	Testing Upgrade Path for Saved Settings	public interface ISettingsUpgrader\n{\n    void UpgradeSettings();\n}\n\npublic abstract class SettingsUpgrader : SettingsUpgrader\n{\n    protected int version;\n\n    public virtual void UpgradeSettings()\n    {\n        // load settings and read version info\n        version = settingsVersion;\n    }\n}\n\npublic class SettingsUpgraderV2 : SettingsUpgrader\n{\n    public override void UpgradeSettings()\n    {\n        base.UpgradeSettings();\n        if(version > 1) return;\n\n        // do the v1 -> v2 upgrade\n    }\n}\n\npublic class SettingsUpgraderV3 : SettingsUpgraderV2\n{\n    public override void UpgradeSettings()\n    {\n        base.UpgradeSettings();\n        if(version > 2) return;\n\n        // do the v2 -> v3 upgrade\n    }\n}	0
15020126	15020041	How to create url route for specific Controller and Action in asp.net mvc3	routes.MapRoute(\n    "Home",\n    "Home/{action}/{id}",\n    new { controller = "Home", action = "Index", id = "" }\n);	0
34524916	34523419	Select text from a list view when that is cliked C# Metro App	private void lsvObjectives_ItemClick(object sender, ItemClickEventArgs e)\n{\n    objectives item = e.ClickedItem as objectives;\n    var itemText = item.objective;\n\n    youtTextBox.Text = item.Description.ToString();\n}	0
4007787	4007782	The order of elements in Dictionary	KeyValuePair<TKey, TValue>	0
12117741	12117569	How to associate tables on insert in LINQ?	CustomerDataContext dc = new CustomerDataContext();\nTable<Customer> customers = dc.GetTable<Customer>();\nTable<Product> products= dc.GetTable<Product>();\nTable<ProductConsumer> ProductConsumers= dc.GetTable<ProductConsumer>();\n\nCustomer newCustomer = new Customer ();\nProduct newProduct   = new Product();\n\n\ncustomers.InsertOnSubmit(newCustomer);\nproducts.InsertOnSubmit(newProduct);\ncustomers.Context.SubmitChanges();\nproducts.Context.SubmitChanges();\n\n//Now insert associations\nProductConsumer= new ProductConsumer();\nProductConsumer.Consumer= newCustomer ;\nProductConsumer.Product= newProduct  ;\n\n\nProductConsumers.InsertOnSubmit(ProductConsumer)\nProductConsumers.Context.SubmitChanges();	0
7004094	7004067	How to eliminate the duplication in these 2 interfaces caused by using struct as parameter?	public interface IJobListener<TDes>\n{\n    void CopyS3File(S3Location src, TDes des, Action<Exception> complete);\n}	0
18804582	18804394	How to wait in loop without blocking UI in C#	private async void MassInvoiceExecuted()\n{     \n    foreach (Invoice invoice in Invoices)\n    {\n        DoStuff(invoice);\n        RefreshExecuted();\n        await Task.Delay(8000);\n    }\n}	0
2340409	2340370	Binary search tree traversal that compares two pointers for equality	t = tree.Root;\nwhile (true) {\n  while (t.Left != t.Right) {\n    while (t.Left != null) {   // Block one.\n      t = t.Left;\n      Visit(t);\n    }\n    if (t.Right != null) {     // Block two.\n      t = t.Right;\n      Visit(t);\n    }\n  }\n\n  while (t != tree.Root && (t.Parent.Right == t || t.Parent.Right == null)) {\n    t = t.Parent;\n  }\n  if (t != tree.Root) {        // Block three.\n    t = t.Parent.Right;\n    Visit(t);\n  } else {\n    break;\n  }\n}	0
1621851	1621001	How to draw string on an image to be assigned as the background to a control in Winforms?	Image i = new Bitmap(200, 50);\nGraphics g = Graphics.FromImage(i);\ng.DrawString("Message", new Font("Arial", 8), Brushes.Black, new PointF(0,0));\n\npictureBox.Image = i;\ng.Dispose();	0
33656340	33654149	Autofac Injection of data into OWIN Startup class	WebApp.Start	0
21630257	21613590	Display a Devexpress UseControl as a Dialog	myForm.ShowDialog()	0
23885290	23885219	How to get top 4 result from a list using linq c#	var t = (from li in list\n         orderby li descending\n         select li).Take(4);	0
26161393	26161334	mySQL through c# writing data to database	MySqlConnection connection = new MySqlConnection(MyConString);\nconnection.Open();\n\n...\n\nMySqlCommand SQLup = new MySqlCommand(mySQL, connection);\nSQLup.ExecuteNonQuery();	0
3802980	3802881	Binding to nested Property of Custom Object	{Binding car.wheels}	0
16523754	16523399	Extracting detail from a WFC FaultException response	MessageFault msgFault = ex.CreateMessageFault();\nvar msg = msgFault.GetReaderAtDetailContents().Value;	0
9453762	9453731	How to calculate distance similarity measure of given 2 strings?	private static int  CalcLevenshteinDistance(string a, string b)\n    {\n    if (String.IsNullOrEmpty(a) || String.IsNullOrEmpty(b))  return 0;\n\n    int  lengthA   = a.Length;\n    int  lengthB   = b.Length;\n    var  distances = new int[lengthA + 1, lengthB + 1];\n    for (int i = 0;  i <= lengthA;  distances[i, 0] = i++);\n    for (int j = 0;  j <= lengthB;  distances[0, j] = j++);\n\n    for (int i = 1;  i <= lengthA;  i++)\n        for (int j = 1;  j <= lengthB;  j++)\n            {\n            int  cost = b[j - 1] == a[i - 1] ? 0 : 1;\n            distances[i, j] = Math.Min\n                (\n                Math.Min(distances[i - 1, j] + 1, distances[i, j - 1] + 1),\n                distances[i - 1, j - 1] + cost\n                );\n            }\n    return distances[lengthA, lengthB];\n    }	0
6092636	6092463	How can I manually add data to a dataGridView?	row.Cells[0].Value = i.ToString();	0
8018121	8018037	JQuery AJAX response value to a label	.html(htmlString)	0
26942699	26927977	How To Add Text Footer Using MimeKit	var part = message.BodyParts.OfType<TextPart> ().FirstOrDefault ();\npart.Text += Environment.NewLine + footer;	0
17018815	17018646	EntityCommandExecutionException was unhandled see innerException for Details	var query = from item in db.People\n            select item.Name;	0
21950975	21950873	How to make multiple listboxes change the value when one of the value in a listbox is clicked?	private void ListBox5_Click(System.Object sender, System.EventArgs e)\n{\n    ListBox lb = (ListBox)sender;\n    if (lb.SelectedIndex != -1) {\n        ListBox1.SelectedIndex = lb.SelectedIndex;\n        ListBox2.SelectedIndex = lb.SelectedIndex;\n        ListBox3.SelectedIndex = lb.SelectedIndex;\n        ListBox4.SelectedIndex = lb.SelectedIndex;\n        ListBox5.SelectedIndex = lb.SelectedIndex;\n        txtsn.Text = ListBox1.SelectedItem;\n        txtsa.Text = ListBox2.SelectedItem;\n        txtsadd.Text = ListBox3.SelectedItem;\n        txtsp.Text = ListBox4.SelectedItem;\n        txtse.Text = ListBox5.SelectedItem;\n    }\n}	0
19696663	19696631	Calling abstract method from an object of derived/base class	abstract class classA\n{\n    public abstract void MyMethod();\n    // other fields and methods\n}\n\ninternal class classB : classA\n{\n    public override void MyMethod()\n    {\n        //logic\n    }\n}\n\ninternal class classC : classA\n{\n    public override void MyMethod()\n    {\n        //logic\n    }\n}	0
8006186	8006135	Unsubscribing events in case variable closure	class MyClass\n{\n    public event EventHandler MyEvent;\n\n    public MyClass()\n    {\n        MyEvent += OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;\n    }\n\n    protected void OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice(object sender, EventArgs e)\n    {\n        MyEvent -= OnSomeEventHandlerToMyLocalClassWhichOfcourseIsABadPractice;\n    }\n}	0
17765056	17764771	How to solve Url encode and decode issue with some special character and numbers	string encodedUrl = HttpContext.Current.Server.UrlEncode(Request.QueryString["QueryString"]);\nstring decodedUrl HttpContext.Current.Server.UrlDecode(encodedUrl);	0
5325631	5271773	WPF: hide grid rows with GridSplitter	public class HideableGridSplitter : GridSplitter\n    {\n        private GridLength height;\n\n        public HideableGridSplitter()\n        {\n            this.IsVisibleChanged += HideableGridSplitter_IsVisibleChanged;\n        }\n\n        void HideableGridSplitter_IsVisibleChanged(object sender, DependencyPropertyChangedEventArgs e)\n        {\n            Grid parent = base.Parent as Grid;\n            if (parent == null)\n                return;\n            int rowIndex = Grid.GetRow(this);\n            if (rowIndex + 1 >= parent.RowDefinitions.Count)\n                return;\n            var lastRow = parent.RowDefinitions[rowIndex + 1];\n\n            if (this.Visibility == Visibility.Visible)\n                lastRow.Height = height;\n            else\n            {\n                height = lastRow.Height;\n                lastRow.Height = new GridLength(0);\n            }\n        }\n    }	0
27671628	27671590	Largest File in Directory	long largestSize = 0;\nfor (int i = 0; i < files.Length; i++)\n{\n    if (files[i].Length > largestSize)\n         largestSize = files[i].Length;\n}\nConsole.WriteLine(largestSize);	0
468164	468155	Transforming a one to many sql query into a List of nested classes	var result = myList\n  .GroupBy(x => x.Id)\n  .Select(g => new Parent()\n  {\n    Key = g.Key,\n    Children = g.Select(x => x.SomeString).ToList()\n  });	0
33234205	33232586	Async Tasks fetching json from api's not runnin async	[System.Web.Http.AcceptVerbs("GET", "POST")]\n[System.Web.Mvc.HttpGet]\npublic async Task<string> ServiceModelsForTournamentBase(int id)\n    {\n        var jsons = await Task.WhenAll(\n              GetJsonFromApi("api/asyncdata/searchmatchfortournament/" + id, _siteUrl),\n              GetJsonFromApi("api/asyncdata/scoringplayersfortournament/" + id, _siteUrl),\n              GetJsonFromApi("api/asyncdata/tournamentteams/" + id, _siteUrl)\n        );\n        var matchInfoJson = jsons[0];\n        var scoringPlayersJson = jsons[1];\n        var teamsJson = jsons[2];\n\n    // return json containing all three\n    }	0
3158748	3142421	Reading first row using ODBC text driver	ColNameHeader=False	0
3402598	3402563	if else Statement in stored procedure?	IF NOT EXISTS (SELECT SerialNumber WHERE SerialNumber = @SerialNumber AND Status = 'Allocated')\nBEGIN\n//Logic for if the serial number is not allocated\nEND\nELSE\nBEGIN\n//Logic for the serial number being in the allocated state\nEND	0
22059111	22058697	C# - WinRT - Convert IPv4 address from uint to string?	uint ip = 0xFFDF5F4F;\n        var bytes = BitConverter.GetBytes(ip);\n        string res = string.Join(".", bytes.Reverse());	0
28054206	28054177	Boolean version to see if list has any values	if(myList.Any())\n{ /* do something */ }	0
15919114	13259723	Extracting value from string	This[\w|\s]*: (?<title>[\w|\s]+)\.	0
18433788	18433735	custom role provider namespace missing	using System.Web.Security;	0
11679409	11536790	How to sort gridview by custom label in the row	protected void grid_CustomColumnSort (object sender, DevExpress.Web.ASPxGridView.CustomColumnSortEventArgs e) {\n    if (e.Column.FieldName == "cTotalValue") \n    {\n        e.Handled = true;\n\n        //you can get the row index of 2 columns being sorted through e.ListSourceRowIndex1 and e.ListSourceRowIndex2\n        //Get the two custom values and compare and set result\n\n        var value1 = "Some custom value you retrieve using e.ListSourceRowIndex1";\n        var value2 = "Another custom value you retrieve using e.ListSourceRowIndex2";\n\n        if (value1 > value2)\n            e.Result = 1;\n        else if (value1 == value2)\n            e.Result = Comparer.Default.Compare(value1, value2);\n        else\n            e.Result = -1;\n    }\n}	0
34332071	34331595	Parse RSS pubdate to DateTime	string parseFormat = "ddd, dd MMM yyyy HH:mm:ss zzz";\n  DateTime date = DateTime.ParseExact(dateString, parseFormat,\n                                            CultureInfo.InvariantCulture);	0
14210413	14210369	Initialize an integer array with a single value in C# .NET	int[] myIntArray = Enumerable.Repeat(-1, 20).ToArray();	0
10866757	10866721	Pin a zero-length array with the fixed keyword	if (aLength == 0) a = new int[1];\nif (bLength == 0) b = new int[1];\nif (cLength == 0) c = new int[1];\nif (dLength == 0) d = new int[1];\nif (eLength == 0) e = new int[1];	0
19763861	19763502	Add header to EndpointAddress	AddressHeader header = AddressHeader.CreateAddressHeader(authorization);\nvar address = new EndpointAddress(ClientConfig.Endpoint, new[] { header });	0
10710014	10709752	Datavisualization datetime axis quarterly format	string lblText = CustomLabelFunction(Chart1.Series["Default"].Points[0]);\nChart1.Series["Default"].Points[0].AxisLabel = lblText;	0
25371745	25371652	ASP Postback deleting data	public List_id_model Model\n{\n  get\n  {\n    List_id_model model = ViewState["List_id_model"] as List_id_model;\n    if (model != null)\n       return model;        \n    return new List_id_model();\n  }\n  set\n  {\n    ViewState["List_id_model"] = value;\n  }\n}\n\nprotected void DropDown_Client_SelectedIndexChanged(object sender, EventArgs e)\n{\n    List_id_model client_list = Model;\n    if (client_list.client_id == null)\n       client_list.client_id = new List<int>();\n    client_list.client_id.Add(value);\n    Model = client_list;\n}	0
18889693	18889089	joining two lists in linq with a field as an array in one list and simple string in other list in C# Linq	var result = from objPt in lstTicketPrintingTrack    \n             join objtransDetail in lstTrans \n             on new { t1 = objPt._id, t2 = } equals new { t1 = objtransDetail._id, t2 = }\n\n             where objPt.Seg.Contains(objtransDetail.transSeq)\n             select new { name = objPt.GetValue("_id").GetIntValue() };	0
5450900	5440651	XML Node Access	EquateType = element.Elements().First().Name.LocalName;	0
9950919	9950766	A button that can ONLY be used by clicking. No Enter, no Return. Just clicks	Button.MouseClick	0
1098810	1098630	How to use C# to get column's description of Sql Server 2005?	t.Columns["ProductID"].ExtendedProperties["MS_Description"].Value	0
13580757	13580602	How to know if a process is using a Network Interface?	ManagedIpHelper.GetExtendedTcpTable(true);	0
13854471	13854391	Make a Listerner to detect Memory usage	Thread.Sleep(1000)	0
9619759	9619704	What can I use to get name string templating that goes beyond String.Format?	string template = \n  @"<html>\n      <head>\n        <title>Hello @Model.Name</title>\n      </head>\n      <body>\n        Email: @Html.TextBoxFor(m => m.Email)\n      </body>\n    </html>";\n\n  var model = new PageModel { Name = "World", Email = "someone@somewhere.com" };\n  string result = Razor.Parse(template, model);	0
2903884	2903668	how to change culture date format in c#?	Thread.CurrentThread.CurrentCulture = New CultureInfo("th-TH", False)	0
7648514	7648480	Create a cookie using Windows Forms C# Application?	internal static class MySharedInfo {\n    /* static proerties and whatever you need */\n}	0
13844679	13844602	Passing a string variable between two foreach-loops in one method	...\n    string adep = let.Attributes.GetNamedItem("adep").Value;\n    string qfu = string.Empty;\n    foreach(XmlNode letiste in getQfu)\n    {\n       if(adep == letiste.Attributes.GetNamedItem("icao").Value);\n            qfu = letiste.Attributes.GetNamedItem("rwy").Value;\n    }\n    ...	0
13691550	13691493	Deserialization of Json without name fields	public TFLB BusRouteMapper(string[] input)\n{\n    return new TFLB {\n        Route = input[x],\n        Direction = input[y],\n    };\n}	0
18142661	18142456	how to insert data into two tables at a time using entity framework	private void AddProducts(double salePrice, int taxValue)\n{\n    using (var ctx = new Entity())\n    {\n\n        Product prodObject = new Product\n        {\n            PId = //NEW ID,\n            SalePrice = salePrice\n        };\n\n        Product_tax pTax = new Product_tax \n        {\n            pid = prodObject.PId,\n            taxid = taxValue\n        };\n\n        ctx.product.AddObject(prodObject);\n        ctx.Product_tax .AddObject(pTax);\n\n        ctx.SaveChanges();\n    }\n}	0
3110313	3110280	How to use reflection to call method by name	MethodInfo method = service.GetType().GetMethod(serviceAction);\nobject result = method.Invoke(service, new object[] { request });\nreturn (R) result;	0
10954961	10954868	making link disappear from window.open pop up	function OpenPopup()\n{\n  document.getElementById("linkID").style.visibility='hidden';\n  window.open("mytest.aspx");\n}	0
22728891	22728814	How to use output parameter and select query result of a sql server stored procedure in ado.net?	With cmd.Parameters\n        cn.Open()\n        dr = cmd.ExecuteReader(CommandBehavior.CloseConnection)\n        ' Process rowset(s)\n        bolEOF = dr.Read\n        Do\n            Do While bolEOF = True\n                ' Process rows\n                bolEOF = dr.Read()\n            Loop\n        Loop While dr.NextResult = True\n        cmd.Cancel()\n// you need to close dataReader first\n        dr.Close()\n\n\n        Debug.WriteLine("@iOutDistinceBankCount:" & _\n            .Item("@iOutDistinceBankCount").Value.ToString)\n    End With	0
10974929	10974735	How to reference aggregate root's property/field while initializing child items	var order = new Order\n{\n    OrderId = 1,\n    OrderDate = new DateTime(2012, 6, 1),\n    OrderStatus = "OPEN",\n    CreatedDate = DateTime.Now\n};\norder.OrderItems = new[]{\n    new OrderItem {\n        LineItemId = 1,\n        ProductId = "Orange",\n        CreatedDate = order.CreatedDate\n    },\n    new OrderItem {\n        LineItemId = 2,\n        ProductId = "Pear",\n        CreatedDate = order.CreatedDate\n    }};	0
5071975	5071849	LINQ to SQL exception when attempting to insert a new entry in a database table	User user = new User();\n\nuser.Id = Guid.NewGuid();	0
10807816	10806401	How to make a button that just cleans up text boxes data?	protected void Button1_Click(object sender, EventArgs e)\n {\n    foreach (TextBox i in this.Page.Form.Controls.OfType<TextBox>().ToList())\n    {\n        i.Text = null;\n    }\n }	0
32188761	32188598	Web Api Server Side Processing and DataTables parameters	public DataTableResult Get([FromUri]DataTableParameters parameters)\n {\n      return new DataTableResult();\n }	0
6456126	6456089	How can I get the Value of a Control by iterating through its parent ControlPanel	if (!(item is Label | item is LiteralControl))\n{\n      if(item is TextBox)\n      {\n        TextBox textBox = (TextBox)item;\n        string textValue = textBox.Text;\n      }\n      ...\n\n}	0
29555597	29542619	Get the 'Nullable' state programmatically of a Property in Entity Framework	var tableName = "someTable";\nvar oc = ((IObjectContextAdapter)context).ObjectContext;\n\nvar items = oc.MetadataWorkspace.GetItems(DataSpace.SSpace).OfType<EntityType>();\nforeach (var entityType in items.Where(e => e.Name == tableName))\n{\n    var props = string.Join(",", entityType.Properties.Where(p => p.Nullable));\n    Debug.WriteLine(string.Format("{0}: {1}", entityType.Name, props));\n}	0
24272285	24255686	Why does generating a mini dump inside a UnobservedTaskException raise an AccessViolationException	ntdll.dll!NtWaitForSingleObject()\nKernelBase.dll!WaitForSingleObjectEx()\nmsvcr110_clr0400.dll!__C_specific_handler()\nntdll.dll!RtlpExecuteHandlerForException()\nntdll.dll!RtlDispatchException()\nntdll.dll!KiUserExceptionDispatch()\ndbghelp.dll!MiniDumpWriteDump()\n[Managed to Native Transition]  \n    ExceptionTest.exe!ExceptionTest.Program.WriteMiniDump() Line 66 C#\nExceptionTest.exe!ExceptionTest.Program.HandleUnobservedTaskException(object sender, System.Threading.Tasks.UnobservedTaskExceptionEventArgs e) Line 48 C#\nmscorlib.dll!System.Threading.Tasks.TaskScheduler.PublishUnobservedTaskException(object sender, System.Threading.Tasks.UnobservedTaskExceptionEventArgs ueea)\nmscorlib.dll!System.Threading.Tasks.TaskExceptionHolder.Finalize()	0
194259	194247	How do I create a string from one row of a two dimensional rectangular character array in C#?	// For the multi-dimentional array\nStringBuilder sb = new StringBuilder();\nfor (int stringIndex = 0; stringIndex < s.Length; stringIndex++)\n{\n  sb.Clear();\n  for (int charIndex = 0; charIndex < str.UpperBound(1); charIndex++)\n    sb.Append(str[stringIndex,charIndex]);\n  s[stringIndex] = sb.ToString();\n}\n\n// For the jagged array\nfor (int index = 0; index < s.Length; index++)\n  s[index] = new string(str[index]);	0
24663146	24596736	Office 365 REST API - Creating a Contact gives me HTTPCode 400	createResponse["GivenName"] = "Rohit1";\n        request.Content = new StringContent(JsonConvert.SerializeObject(createResponse));\n        request.Content.Headers.ContentType = new MediaTypeHeaderValue("application/json");	0
7243823	7243751	how replace all spaces in a text file with one character?	System.IO.File.WriteAllLines(\n    "outfilename.txt",\n    System.IO.File.ReadAllLines("infilename.txt").Select(line =>\n        string.Join("|",\n            line.Split(new string[] { " " }, StringSplitOptions.RemoveEmptyEntries)\n        )\n    ).ToArray()\n);	0
19014198	18399102	Login Failed - LocalDB, EF, WebSecurity	System.Data.Entity.Database.SetInitializer<EFDbContext>(new DropCreateDatabaseAlways<EFDbContext>());\n// System.Data.Entity.Database.SetInitializer<EFDbContext>(EFDbContext>(null);\n\nif (!WebMatrix.WebData.WebSecurity.Initialized)\n {\n     WebSecurity.InitializeDatabaseConnection("EFDbContext", "UserProfile", "UserId", "UserName", autoCreateTables: true);\n }	0
27122041	27121723	Searching Tri Data Structure	private void searchBox_TextChanged(object sender, TextChangedEventArgs e)\n{\n    listboxWords1.Items.Clear();\n\n    if (searchBox.Text.Length > 0)\n    {\n        trie.Matcher.ResetMatch();//Reset the match\n\n        foreach (char c in searchBox.Text)\n            trie.Matcher.NextMatch(c); //Start the match from beginning \n\n        foundWords = trie.Matcher.GetPrefixMatches(); //foundWords is List<string>\n        for (int i = foundWords.Count - 1; i > 0 ; i--)\n        {\n            listboxWords1.Items.Add(foundWords[i]);\n        }\n\n        foundWords = null;\n        isFoundExact = trie.Matcher.IsExactMatch();\n        if (isFoundExact)\n            listboxWords1.Items.Add(trie.Matcher.GetExactMatch());\n    }\n    else\n    {\n        foundWords = null;\n        trie.Matcher.ResetMatch();    \n    }\n}	0
31181643	31178797	Delete selected rows from DataGridView after password is correct	private void btnOK_Click(object sender, EventArgs e)\n{\n    if(textbox.Text=="admin")\n    {\n    var form = Application.OpenForms.OfType<Meniu>().Single();\n    form.DeleteSelectedRows();\n    }\n}	0
22923141	22922881	JSON with dynamic Root-Object	JObject obj = JObject.Parse(json);\nif (obj != null)\n{\n    var root = obj.First;\n    if (root != null)\n    {\n        var sumJson = root.First;\n        if (sumJson != null)\n        {\n            var sum = sumJson.ToObject<Sum>();\n        }\n    }\n}	0
17243080	17242971	Broadcasting message to all clients except self in SignalR	Clients.Others.addMessage(message)	0
10073953	10073452	Grid View in Asp.net C# with wamp Server's MYSQL	datagridview.Datasource = datasource\ndatagridview.databind()	0
20855298	20854641	How to make a windows forms application in C# that can receive data from a serial port	var frm = new Form { Height = 200, Width = 200 };\nvar txt = new TextBox {Dock = DockStyle.Fill, Multiline=true };\nfrm.Controls.Add(txt);\nport.DataReceived += (sender, args) => { \n        if (txt.InvokeRequired)\n        {\n            txt.Invoke(new MethodInvoker(() => { \n                txt.Text += port.ReadExisting(); \n                }));\n        } \n        else  \n        {\n           txt.Text += port.ReadExisting(); \n        }\n   };\nApplication.Run( frm);	0
876618	876519	Displaying random images at runtime	private void Page_Load( object sender, EventArgs e ) {\n    string imgUrl = GetRandomImageUrl();\n    Session["num1"] = imgUrl;\n    Image1.ImageUrl = imgUrl;\n    Image1.Visible = true;\n}\n\nprotected string GetRandomImageUrl() {\n    Random r = new Random();\n    return String.Format( "~/fordoctor/doctor_login/images/{0}.gif", r.Next( 0, 9 ) );\n}	0
32691540	32691519	How to specify a class that may contain another class	public class ServerResponseObject<T>\n{\n    public ServerResponseObject(T obj)\n    {\n        Obj = obj;\n    }\n\n    public T Obj { get; set; }\n}	0
11835508	11835462	c# mysql statement string	string stm = @"\n    select distinct(position)\n      from plan \n     where region = @region\n       and market = @market\n";\n\n\nMySqlCommand cmd = new MySQLCommand(stm);\ncmd.Parameters.AddWithValue("@region",regionvalue);\ncmd.Parameters.AddWithValue("@market",marketvalue);	0
14613690	14613628	Create a new String with Duplicate Letters	var original = "stack";\nfor (int i = 0; i < original.Length; i++)\n    Console.WriteLine(original.Insert(i, original[i].ToString()));	0
23625687	23563215	How to add attribute value in xml	XmlNode RootNode = doc.CreateElement("SDF");\n            doc.AppendChild(RootNode);\n            XmlAttribute rootAttribute2 = doc.CreateAttribute("Version");\n            rootAttribute2.Value = "3.0";\n            RootNode.Attributes.Append(rootAttribute2);\n            XmlAttribute newAttr = doc.CreateAttribute("sdf", "noNamespaceSchemaLocation", "http://www.w3.org/2001/XMLSchema-instance");\n            newAttr.Value = "SDF.xsd";\n            RootNode.Attributes.Append(newAttr);	0
14921239	14921185	getting rid of white space in List<string> that resides in Dictionary	// source dictionary\nDictionary<string, List<string>> dict = new Dictionary<string, List<string>>();\n\n// target dictionary\nDictionary<string, List<string>> target = new Dictionary<string, List<string>>();\n\n// using LINQ extension methods\ndict.ToList().ForEach(i =>\n{\n    List<string> temp = i.Value.Select(x => x.Trim()).ToList();\n    target.Add(i.Key, temp);\n});	0
6691891	6691833	how to take all the files with `.flg` Extension and put the numbers on a list	DirectoryInfo di = new DirectoryInfo(@"c:\temp\");\nFileInfo[] fis = di.GetFiles("*.flg");\nforeach (FileInfo fi in fis)\n{\n    Console.WriteLine("File Name: {0}, Full Name: {1}, Number: {2}", fi.Name, fi.FullName, fi.Name.Substring(fi.Name.LastIndexOf(".") - 3, 3));\n}	0
8744751	8720633	Using query string parameters to disambiguate a UriTemplate match	[OperationContract]\n[WebGet(UriTemplate = "people/driversLicense/{driversLicense}")]\nstring GetPersonByLicense(string driversLicense);\n\n[OperationContract]\n[WebGet(UriTemplate = "people/ssn/{ssn}")]\nstring GetPersonBySSN(string ssn);	0
6048548	6040920	Display an image contained in a byte[] with ASP.Net MVC3	public FileContentResult Display(string id) {\n   byte[] byteArray = GetImageFromDB(id);\n   return new FileContentResult(byteArray, "image/jpeg");\n}	0
592841	592747	Can any one recommend a vector graphics engine for reporting purposes?	using System.Drawing;\n\n...\n\nFont font = new Font(FontFamily.GenericMonospace, 8);\nImage reportImage = new Bitmap(270, 45);\nusing (Graphics graphics = Graphics.FromImage(reportImage))\n{\n    graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;\n\n    graphics.FillRectangle(Brushes.White, \n        new Rectangle(new Point(0, 0), reportImage.Size));\n\n    for (int i = 0; i != 6; i++)\n    {\n        Rectangle r = new Rectangle(20 + i * 40, 15, 25, 15);\n        graphics.FillEllipse(\n            i % 2 == 0 ? Brushes.DarkOrange : Brushes.DarkKhaki, r);\n        graphics.DrawEllipse(Pens.Black, r);\n\n        r.Offset(2, 0);\n\n        graphics.DrawString(i.ToString(), font, Brushes.Black, r);\n    }\n}\nreportImage.Save("C:\\test.bmp");	0
11750082	11750064	How do I access a variable that is inside a Class that is inside a List?	library.books[0].name	0
23878925	23878871	c# Regex Date in brackets	\[0*([1-9]|[12][0-9]|3[01]) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (201[4-9]|20[2-9][0-9]|2[1-9][0-9]{2}|[3-9][0-9]{3}) ((?:0?[0-9]|1[0-9]|2[0-3]){2}:(?:0?[0-9]|[1-5][0-9])) by (\w+)\]	0
15027848	15020522	Add new Window from C# Code-Behind in ext.net	// Old\n// editwindow.Add(editpanel);\n// this.Page.Controls.Add(editwindow);\n\n// New\neditwindow.Items.Add(editpanel);\neditwindow.Render(this.Form);	0
855324	854666	How to write to the Console input and get the Console Handle?	System.Console	0
31450042	31448542	Trying to grab specific number from variable	int health = 100;\nint lastFrameHealth;\n\nvoid Start ()\n{\n    lastFrameHealth = health;\n}\n\nvoid Update ()\n{\n    if (health < lastFrameHealth)\n    {\n        StartCoroutine("InterruptPassiveSkill", 5f);\n    }\n\n    lastFramehealth = health;\n}\n\n\nvoid OnCollisionEnter(Collision collision)\n{\n    health -= 10;\n}\n\nIEnumerator InterruptPassiveSkill (float seconds)\n{\n    // insert code to deactivate passive skill here:\n\n    yield return new WaitForSeconds(seconds); // delay for number of seconds\n\n    // insert code to reactivate passive skill here:\n\n}	0
5939438	5939404	Complement of Two Lists?	var result = list1.Except(list2);	0
4625188	4625047	Looking for a Regex to get SccTeamFoundationServer value from .sln file	\bSccTeamFoundationServer\s*=\s*(['"]?)([^\1\n]*)\1	0
9672324	9672297	Reading values from a DataTable column into a List<string> with LINQ	table.AsEnumerable().Select(dr => dr.Field<string>("FuncName")).ToList()	0
22296684	22296504	Set a wait time for a statement in C#	webclient.Timeout = 500;\nreturnValue = webclient.uploadstring(url, Message);	0
17466128	17464607	C# contains method for white spaces	if (test.ToLower().Replace('\u00A0', ' ').Contains("hello stack person"))\n{\n    // code\n}	0
20019440	20019152	Insert new row to database with computed columns	[DatabaseGenerated(DatabaseGeneratedOption.Computed)]	0
2251004	2250660	2 variable switch loop	foreach( DataRow row in workingTable.Rows ) \n{\n    int keyIndex = isKey ? keyIdentifier : sKeyIdentifier;\n    int valueIndex = isValue ? valueIdentifier : sValueIdentifier;\n\n    workingDictionary.Add( row[ keyIndex ].ToString(), row[ valueIndex ] );                             \n}	0
26165038	26164206	C# Waiting for an action in a parallel thread	public class DataViewModel\n{\n    public AsynchronousCommand Send;\n\n    public DataViewModel()\n    {\n        Send = new AsynchronousCommand(() =>\n        {\n            SendData();\n        });\n    }\n\n    private void SendData()\n    {\n    }\n}\n\npublic class SomewhereInForm\n{\n    private DataViewModel dataViewModel = new DataViewModel();\n\n    public SomewhereInForm()\n    {\n        dataViewModel.Send.Executed += SendOnExecuted;\n    }\n\n    private void SendOnExecuted(object sender, CommandEventArgs args)\n    {\n    }\n\n    private void DoSome()\n    {\n        dataViewModel.Send.DoExecute(new int());\n    }\n}	0
8172477	8172334	Select row in paging gridview based on unique cell value	gvFrame.SelectedIndex = gvFrame.Rows.Cast<GridViewRow>().First(r => \n    (string)gvFrame.DataKeys[r.RowIndex]["foo"] == requestedFrame).RowIndex;	0
15151820	15151749	Displaying selected data in a datagridview	string query = "SELECT * FROM Employee WHERE LastName='"+ textBox1.Text +"'";	0
12029157	12028246	Attaching database to my project	bin\debug	0
18824347	18636416	assign values from table to Dhtmlx scheduler config	var data = _config.GetSettings().ToDictionary(\n                s => s.Desc, \n                s => s.Setting, \n                StringComparer.Ordinal);\n\n\nif(data.ContainsKey("start time"))\n    scheduler.Config.first_hour = int.Parse(data["start time"]);\n\nif (data.ContainsKey("end time"))\n    scheduler.Config.first_hour = int.Parse(data["end time"]);	0
20900896	20900555	Unit testing dialog boxes pop ups using moq in mvvm prism based application	public interface IUIService   \n        {   \n            bool ShowPopUp(....);\n\n            DialogResult ShowDialog(...);\n\n            ..  \n        }	0
1270452	1270433	How to write multiple textboxes into a programme generated txt file in C#?	StreamWriter writeFile = new StreamWriter(fileLocation);\nwriteFile.WriteLine(textBox1.Text);\nwriteFile.WriteLine(textBox2.Text);\n//etc.\n\nwriteFile.Close();	0
4366451	4366422	How to remove characters from a string using LINQ	new string("XQ74MNT8244A".Where(char.IsDigit).ToArray()) == "748244"	0
9240223	9240102	Finding intrecept points for two line shape in c#	(verticalLine.Start.X, horizontalLine.Start.Y)	0
759346	759310	Best way of dynamically setting color of control at runtime	txt.ForeColor = System.Drawing.Color.FromName("#00B300");\ntxt.ForeColor = System.Drawing.Color.FromName("red");	0
11784068	11781670	CaptchaMVC image route not working with my current routes in MVC3 - how to resolve?	routes.MapRoute(name: "DefaultCaptchaRoute", url: "DefaultCaptcha/Generate", defaults: new { controller = "DefaultCaptcha", action = "Generate" });	0
11824924	11824875	Programmatically checking a connection string username/password?	SqlConnection conn = new SqlConnection (yourconnectionstring + ";Connection Timeout=1;");          \n try\n { \n     conn.Open();\n     conn.Close();\n }\n catch (SqlException ex)\n {\n     if (ex.Number == 18456)\n     {\n          // invalid login\n     }\n }	0
98572	98559	How to parse hex values into a uint?	Convert.ToUInt32(hex, 16)  //Using ToUInt32 not ToUInt64, as per OP comment	0
4466741	4466428	How to create SQL Server 2008 database full backup programmatically in desired folder	BACKUP DATABASE database_name TO DISK='d:\path\to\backup\file\on\the\server.bak'	0
4589965	4589938	Finding a line in a string, and grabbing information from line	namespace ConsoleApplication2 {\n    class Program {\n        static void Main(string[] args) {\n            string line;\n            //initialize Dictionary\n\n            var keyMatch = new Dictionary<string, string>();\n            //opening the file\n            using (TextReader re = File.OpenText("Sample.txt")) {\n                //loop through lines\n                while ((line = re.ReadLine()) != null) {\n                    keyMatch.Add(line.Substring(0, line.IndexOf("-")), line.Substring(line.IndexOf("-") + 1));\n                }\n            }\n\n            var test = keyMatch["Info5"];\n        }\n    }\n}	0
3483645	3483600	Implementation question of the Presenter in MVP	[CreateNew]\npublic DefaultViewPresenter Presenter\n{\n    set\n    {\n        this._presenter = value;\n        this._presenter.View = this;\n    }\n}	0
2577369	2577358	Error loading contents from a XML file into a dropdownlist	private void BindCountry()\n{\n    XmlDocument doc = new XmlDocument();\n    doc.Load(Server.MapPath("countries.xml"));\n\n    foreach (XmlNode node in doc.SelectNodes("//country"))\n    {\n        XmlAttribute attr = node.Attributes["codes"];\n        if (attr != null)\n        {\n            usrlocationddl.Items.Add(new ListItem(node.InnerText, attr.Value));\n        }\n    }\n}	0
32374213	32370326	converting Excel % to C#	double a = 3.332125;\ndouble b = 100/100;\ndouble c = 0 / 100;\nConsole.WriteLine((a * b * (c + 100 / 100) + 0.16).ToString());	0
6722797	6722767	How to best manage multiple streams in a loop in C#	if (genStream == null )\n{\ngenStream.Close()\n}	0
13643944	13643706	Is it possible to set an HTML button as default inside a form?	// JavaScript Code\n   var body = document.getElementsByTagName('body')[0];\n    body.onkeydown = function (e) {\n        if (e.keyCode === 13) {  //enter key code\n         // call your html button onclick code here\n        }\n    }	0
20024409	20024252	How do I pass a string to a function requiring an Object?	//This will cause BuildQueryString to return "actions=createCard&action_fields=data,type,date"\nvar options = new { actions = "createCard", action_fields = "data,type,date" };\n\nList<CardUpdateAction> cua = chello.CardUpdates.ForCard("5264d37736695b2821001d7a",options).ToList();	0
750085	749007	Creating a Loop to Pause a Script While a Callback Function Operates	static ManualResetEvent finishGate;\n\nstatic void Main(string[] args)\n{\n    finishGate = new ManualResetEvent(false); // initial state unsignaled\n\n    Telnet telCon = new Telnet();\n    telCon.OnDataIn += new Telnet.OnDataInHandler(HandleDataIn);\n    telCon.Connect(remoteHostStr);\n\n    finishGate.WaitOne(); // waits until the gate is signaled\n}\n\npublic static void HandleDataIn(object sender, TelnetDataInEventArgs e)\n{\n    // handle event\n\n    if (processingComplete)\n        finishGate.Set(); // signals the gate\n}	0
23053524	23053459	Copying only files in subfolders to destination	List<string> files = new List<string>(Directory.GetFiles(@"C:\test", "*.dll", SearchOption.AllDirectories));\nfiles.ForEach(f => File.Copy(f, Path.Combine(@"C:\dest", Path.GetFileName(f))));	0
11164511	11164452	How to properly exit background thread with loop when class exported via MEF?	this.listenThread = new Thread(this.ListenForClients);\nthis.listenThread.IsBackground = true;\nthis.listenThread.Start();	0
1563378	1563282	Retrieve a list of object implementing a given interface	void GetListByInterface<TInterface>(out IList<TInterface> plugins) where TInterface : IBasePlugin\n{\n  plugins = (from p in _allPlugins where p is TInterface select (TInterface)p).ToList();\n}	0
20895143	20895062	I'm making a C# application that uses MySQL database	DataTable table = new DataTable();\n//put some data in your table and then\ntable.Columns.Add("C1");\ntable.Columns.Add("C2");\nString[] examplerow = new String[] {"one","two"};\ntable.Rows.Add(examplerow);\nDataRow row = table.Rows[0];\nConsole.WriteLine(row["C1"]); // Or pass it to textboxes, etc	0
33946060	33946017	Using a list to receive rows from a database	public List<Users> GetUsers()\n            {\n                List<Users> users=new  List<Users> ();\n                DataSet ds=getDataSet("Select FirstName,...... from Users")\n                Users user;\n\n                 foreach(DataRow row in ds.Tables[0].Rows)\n                 {\n                   user=new Users();\n                   user.FirstName=row["firstname"].ToString();\n                    ....\n                    ....\n                   users.Add(user)\n                 }\n                return users;\n            }	0
10064039	10063986	C# /Javascript /ASP.NET - Changing DIV Contents From A Child Page	div.Controls.Add(control);	0
16023192	16023157	Assign Variable with First Day of the Month	Dim dtFirstOfMonth as DateTime = new DateTime(DateTime.Now.Year, DateTime.Now.Month, 1)	0
13142931	13138243	Entity Framework: Linq query finds entries by original data but returns reference to changed entry	using (var transaction = new TransactionScope())\n{\n\n    var result = from r in db.Tests\n                    where r.value == 10\n                    select r;\n    Test t2 = result.FirstOrDefault();\n\n    // change its value from 10 to 4711...\n    t2.value = 4711;\n    // send UPDATE to Database but don't commit transcation\n    db.SaveChanges();\n\n    var result2 = from r in db.Tests\n                    where r.value == 10\n                    select r;\n    // should not return anything\n    Trace.Assert(result2.Count() == 0);\n\n    // This way you can commit the transaction:\n    // transaction.Complete();\n\n    // but we do nothing and after this line, the transaction is rolled back\n}	0
29743917	29743769	ListView wont update	CONTROL.Invoke(new Action(() =>\n{\n  CONTROL.Items.Add(item);\n}\n));	0
11959512	11959380	How to get the DescriptionAttribute value from an enum member	private string GetEnumDescription(Enum value)\n{\n    // Get the Description attribute value for the enum value\n    FieldInfo fi = value.GetType().GetField(value.ToString());\n    DescriptionAttribute[] attributes = (DescriptionAttribute[])fi.GetCustomAttributes(typeof(DescriptionAttribute), false);\n\n    if (attributes.Length > 0)\n        return attributes[0].Description;\n    else\n        return value.ToString();\n}	0
17004784	17004276	Validate a string's format like a phone number?	var regex = @"\(\d{3}\)-\d{8}-\(\d{3}\)";\nvar matches = Regex.Match("(123)-12345678-(123)", regex);\n\n// this means it did in fact match the input\nif (matches.Success)	0
17759311	17758976	handle events of control dynamically	Protected Sub TabContainer1_ActiveTabChanged(ByVal sender As Object, ByVal e As System.EventArgs) \n    Handles TabContainer1.ActiveTabChanged\n                Dim actTab As String = TabContainer1.ActiveTab.ID.ToString()\n                Dim gv As GridView\n\n                ds = gc.GetDataToListBinder("select * from ParameterOnline where TabName='Courts'")\n\n                If actTab = "Panel_Courts" Then\n                    gv.DataSource = ds.Tables(0)\n                    TabContainer1.ActiveTab.Controls.Add(gv)\n                End If\n\n\n            End Sub	0
1912049	1911578	Prevent scrollbars with WPF WebBrowser displaying content	mshtml.HTMLDocument htmlDoc = webBrowser.Document as mshtml.HTMLDocument;\nif (htmlDoc != null && htmlDoc.body != null)\n{\n    mshtml.IHTMLElement2 body = (mshtml.IHTMLElement2)htmlDoc.body;\n    webBrowser.Width = body.scrollWidth;\n    webBrowser.Height = body.scrollHeight;\n}	0
19661313	19660765	How to install Fiddler's root certificate in Machine Root store	private static bool setMachineTrust(X509Certificate2 oRootCert)\n{\n  try\n  {\n    X509Store certStore = new X509Store(StoreName.Root, \n                                        StoreLocation.LocalMachine);\n    certStore.Open(OpenFlags.ReadWrite);\n\n    try\n    {\n      certStore.Add(oRootCert);\n    }\n    finally\n    {\n      certStore.Close();\n    }\n    return true;\n  }\n  catch (Exception eX) \n  {\n     return false;\n  }	0
2417193	2385317	Dynamic control with DevExpress ASPXComboBox has Javascript problems	protected void Page_Load(object sender, EventArgs e)\n    {\n        base.Page_Load();\n        this.control.DataBind();\n    }	0
13528048	13527474	How to close a form in UserControl	((Form)this.TopLevelControl).Close();	0
1560004	1559983	string replacing - C#	Regex.Replace(input, @"\D+", "")	0
5337623	5337543	how to get datetime with +- 10 seconds Buffer?	Random random = new Random(); \nTimeSpan buffer = TimeSpan.FromSeconds(10);\n\nTimeSpan span = TimeSpan.FromHours(24.0);\n\n// 50% of the time do this\nif(random.Next() % 2 == 0)\n{\n    span += buffer;\n}\n// The rest of the time do this\nelse\n{\n    span -= buffer;\n}\n\njobElement.CreationDate = jobElement.CreationDate + span;	0
27700743	27700683	TimeSpan default value format	// Use TimeSpan constructor to specify:\n// ... Days, hours, minutes, seconds, milliseconds.\n// ... The TimeSpan returned has those values.\nTimeSpan span = new TimeSpan(0, 0, 13, 0, 0);\nConsole.WriteLine(span);	0
12859496	12340135	Hightlight Listbox item on mouse over event	private void pinnedAppsListBox_MouseHover(object sender, EventArgs e){\n\n   Point point = pinnedAppsListBox.PointToClient(Cursor.Position);\n   int index = pinnedAppsListBox.IndexFromPoint(point);\n   if (index < 0) return;\n   //Do any action with the item\n   pinnedAppsListBox.GetItemRectangle(index).Inflate(1,2);\n}	0
6069783	6069725	join List of dates	string.Join(",", dates.Select(d => d.ToString("dd/MM/yyyy")).ToArray());	0
11330187	11330101	Can only send email via Outlook if Outlook is open	app = new Microsoft.Office.Interop.Outlook.Application();\n            Microsoft.Office.Interop.Outlook.NameSpace ns = app.GetNamespace("MAPI");\n            f = ns.GetDefaultFolder(OlDefaultFolders.olFolderInbox);\n            Thread.Sleep(5000); // a bit of startup grace time.	0
13920536	13920292	How to create dynamic mathematical function?	NCalc.Expression expr = new NCalc.Expression("x * 10 / 3");\nexpr.EvaluateParameter += (name, args) =>\n    {\n        if (name == "x" && somecondition == 1) args.Result = 6;\n        if (name == "x" && somecondition == 2) args.Result = 12;\n    };\nvar result = expr.Evaluate();	0
32243168	32239108	Change font style in gridcontrol devexpress?	using DevExpress.XtraGrid.Views.Grid;\n//...\nvoid gridView_RowStyle(object sender, RowStyleEventArgs e) {\n   GridView view = sender as GridView;\n   if(e.RowHandle >= 0) {\n      int value = (int)view.GetRowCellValue(e.RowHandle, view.Columns["ISVERIFIKASI"]);\n      if(value == 1) \n         e.Appearance.Font = ...;\n   }\n}	0
6158537	6158499	object instantiate in one method can access by another method?	public class MyForm : Form \n{\n     Friend f1;\n\n    private void OnLoad()\n    {\n       f1 = new Friend();\n    }\n\n    private void Display()\n    {\n       // use f1 here\n    }\n\n}	0
14803837	14762256	Properly printing a 2D array?	*  \n  * \n****	0
8074225	8074207	How to convert a Delegate to a string of code?	Expression<Action> expr = () => MessageBox.Show("test");\n\nConsole.WriteLine(expr.ToString()); \n// () => Show("test")	0
8584473	8584155	replay a list of functions and parameters	public class Recorder\n{\n    private IList<Action> _recording;\n    public Recorder()\n    {\n        _recording = new List<Action>();\n    }\n    public void CallAndRecord(Action action)\n    {\n        _recording.Add(action);\n        action();\n    }\n    public void Playback()\n    {\n        foreach(var action in _recording)\n        {\n            action();\n        }\n    }\n}\n\n//usage\nvar recorder = new Recorder();\n//calls the functions the first time, and records the order, function, and args\nrecorder.CallAndRecord(()=>Foo(1,2,4));\nrecorder.CallAndRecord(()=>Bar(6));\nrecorder.CallAndRecord(()=>Foo2("hello"));\nrecorder.CallAndRecord(()=>Bar2(0,11,true));\n//plays everything back\nrecorder.Playback();	0
9323189	9322819	How to get a sum of children values on one LINQ	var ListByPrograma  = from a in db.Actions\n join c in db.Costs on a.ID equals c.Action_Id\n group new {a,c} by a.Program into p\n select new\n {\n    Program = p.Key,\n    actionsQty = p.Count ( ),\n    totalValue1 = p.Sum(y => y.c.Value1),\n    totalValue2 = p.Sum (y => y.c.Value2),\n    totalValue3 = p.Sum(y=>y.c.Value3)\n};	0
7691577	7691546	How can I split a string to obtain a filename?	string fileName = "description/ask_question_file_10.htm";\n\nstring result = Path.GetFileNameWithoutExtension(fileName);\n// result == "ask_question_file_10"	0
5773721	5773601	Start Nant from code	var startInfo = new ProcessStartInfo( executable, parameters )\n            {\n                UseShellExecute = false,\n                RedirectStandardError = false,\n                RedirectStandardOutput = false,\n                CreateNoWindow = true\n            };\n\n            using( var process = Process.Start( startInfo ) )\n            {\n                if( process != null )\n                {\n                    process.WaitForExit( timeoutInMilliSeconds );\n                    return process.ExitCode;\n                }\n            }	0
9951865	9951704	Add item to Listview control	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        string[] row = { textBox1.Text, textBox2.Text, textBox3.Text };\n        var listViewItem = new ListViewItem(row); \n        listView1.Items.Add(listViewItem);\n    }\n}	0
21822428	21822252	How to convert WorkItemCollection to a List	testItemCollectionList = (from WorkItem mItem in testItemCollection select mItem).ToList();	0
27327208	20990601	Decompressing GZip Stream from HTTPClient Response	using (var client = new HttpClient(new HttpClientHandler { AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate }))\n{\n    // your code\n}	0
15519816	15519694	Entity framework, unit of work and the order of generated inserts statements	// Build graph\nvar customer = new Customer(...);\ncustomer.LegalAddress = new Address(...);\nvar account = new Account();\naccount.Customer = customer;\nvar order = new Order();\norder.BuyerAccount = account;\n// Here all Navigation properties updated\n// and state of all entities set to Added\n_orderRepository.Add(order); \n// Here all entities inserted in transaction, PK and FK updated\ncontext.SaveChanges();	0
15508794	15507440	SQL DataSource using WHERE IN clause	LUWAccts.SelectCommand = \nString.Format("SELECT mycolumns FROM mytables WHERE GROUP_NAME IN {0})",\nGet_SVCACCT_Auth_Groups(Session["ThisUser"].ToString()));	0
7394363	7394322	RegEx Split - keeping the punctuations	(?<=[.?!])\s*	0
15473769	15473642	how to find the word and split the integer and characters in a string	Regex = new Regex("(\d+)(years?)");\n\nMatch match = regex.Match(ss);\nif(match.Success)\n{\n  string s = match.Groups[1];\n  string s1 = match.Groups[2];\n}	0
1226042	1225983	How can I use a DebuggerDisplay attribute on an indexer class	Debug: {Items[{index}]}	0
5423806	5423736	Get Data From Specific Column	String birthDate = \n    dsEmployees.Employees.FindByEmployeeID(Convert.ToInt32(ID.ToString())).BirthDate.ToString();	0
28804936	28804783	Converting from on type of list to another type	List<Record> t = new List<Record>();\n\n            var result = t.ConvertAll(x => new RecordModified()\n                {\n                    RecordTypeText = ((MyEnum)x.RecordTypeID).ToString()\n                });	0
2309424	2309412	how to recode back? BitConverter	string base64 = Convert.ToBase64String(test);\nbyte[] originalBytes = Convert.FromBase64String(base64);\nstring text = Encoding.ASCII.GetString(originalBytes);	0
27927780	27866716	opening a link in a new window	Uri uri = new Uri(LinkButton.Text);\nScriptManager.RegisterStartupScript(this, Page.GetType(), "", "window.open('" + uri.OriginalString + "');", true);	0
12658211	12657088	Unload Item From Data Context's Local View	var collection = new ObservableCollection<Note>(this.DBContext.Notes.Where(n => n.ID == selectedNote.ID)); \nthis.notesBox.DataContext = collection;	0
4110080	4110016	Calling wrapped C++ DLL method from C#: passing addresses of integral variables to get output	[DllImport("blah.dll")]\nprivate static extern int thingy( ref uint refArg );\n/* ... later in the code. ...*/\nint retVal = thingy( ref refVariable );	0
32999477	32994265	How to get variable "SafeFileNames" from another method?	public Form1()\n{ \n    InitializeComponent();\n}\npublic string[] fileNames { get; private set; }\nint numberOfFiles { get; set; }\n\npublic void button1_Click(object sender, EventArgs e)\n{\n    //Your openFileDialog1 initialisation and other stuff here\n    if (openFileDialog1.ShowDialog() == DialogResult.OK)\n    {\n        fileNames = openFileDialog1.SafeFileNames;\n        numberOfFiles = fileName.Length;\n    }\n}\npublic void button2_Click(object sender, EventArgs e)\n{\n    foreach (string fileName in fileNames)\n    {\n        //You can access the name of each file using fileName now\n    }\n}	0
19464617	19409705	How to clear inserted data into db from button	DELETE FROM table_name\nWHERE some_column=some_value	0
4804393	4804315	Guaranteeing request came from local server	context.Request.IsLocal	0
19295745	19295656	Using an extension method on a base class in a LINQ query	public static IQueryable<T> Active<T>(this IQueryable<T> entityCollection) where T:EntityBase\n{\n    return entityCollection.Where(e => e.Enabled && !e.Deleted);\n}	0
17019229	17007340	Collision detection with tilemap in XNA	if (myMap.Rows[(int)cekPosisiPlayer().Y].Columns[(int)(cekPosisiPlayer().X + (7 / 6))].passable)	0
519923	519872	Turn off request validation programmatically	PagesSection pageSection = new PagesSection();\npageSection.ValidateRequest = false;	0
16449401	16449342	Accessing and getting response from API call	// Get the stream associated with the response.\nStream receiveStream = response.GetResponseStream ();\n\nStreamReader readStream = new StreamReader (receiveStream, Encoding.UTF8);\n\nConsole.WriteLine ("Response stream received.");\nConsole.WriteLine (readStream.ReadToEnd ());	0
13876081	13760795	How to Pass PSCredential object from C# code to Powershell Function	powershell.AddCommand("Set-Variable");\npowershell.AddParameter("Name", "cred");\npowershell.AddParameter("Value", Credential);\n\npowershell.AddScript(@"$s = New-PSSession -ComputerName '" + serverName + "' -Credential $cred");\npowershell.AddScript(@"$a = Invoke-Command -Session $s -ScriptBlock {" + cmdlet + "}");\npowershell.AddScript(@"Remove-PSSession -Session $s");\npowershell.AddScript(@"echo $a");	0
20758591	20758293	Set property (type interface) without implementation	Mock<IFileInformation> fileInformation = new Mock<IFileInformation>();\nfileInformation.SetupGet(x => x.Name).Returns("whatever.txt");\n\nThing serviceResult = new Thing();\nserviceResult.FileInformation = fileInformation.Object;	0
20213310	20213270	How do i remove all white spaces from a string?	images= images.Replace(" ", String.Empty);	0
18347181	18322332	How to add subview above the keyboard in monotouch/Xamarin.Ios?	UIApplication.SharedApplication.Windows[1].AddSubview(myView);	0
2405337	2405322	How to combine elements of a list	var newList = (\n    from trade in FillList\n    group trade by trade.Date.Date into g\n    select new CurrentTrade { date = g.Key, dwBuy = g.Sum(t => t.dwBuy) }\n).ToList();	0
16436729	16436225	Extract InnerText from HTML	HtmlDocument doc = new HtmlDocument();\n doc.Load("file.htm");\n foreach(HtmlNode link in doc.DocumentElement.SelectNodes("//span"])\n {\n\n }	0
2073998	2073902	Property as parameter? C#	return allFoos.All(foo => foo.FooVar1 == defaultFoo.FooVar1);	0
6586869	6586845	RegEx to replace trailing string in specific format	var newStr = Regex.Replace(input, @"\s+[\d\.]+\s*Megapixels", "", RegexOptions.IgnoreCase);	0
27960764	27960571	Write in html with variables, then reset to default	const string fileName = "txt.html";\n const string templateFileName = "txtTemplate.html";    \n\nvar content = File.ReadAllText(templateFileName );\ncontent = content.Replace("{0}", textBox1.Text);\n\nFile.WriteAllText(fileName, content);\n\nProcess.Start(fileName);	0
12508956	12508920	How to know you got no result from the database	if (setTest.Tables[0].Rows.Count == 0)	0
20071788	20071537	Add data from list to list in another class conditionally	....\nformList = data.Read<WebsiteForm>().ToList();\nsurveyList = data.Read<Survey>().ToList();\n\nformList.ForEach(fl=>fl.Surveys = surveyList.Where(sl=>sl.LinkID == fl.ID).ToList());\n....	0
17380281	17380239	Datetime Formatting giving it a specific culture doesn't change how day is printed out	Console.WriteLine(date.ToString("dddd MM-dd-yy",usCultureInfo));	0
6204713	6192906	Can I put a windows (.bat ) file inside the resources folder of a Visual stuido C# project?	string location;\n\nProcess p = new Process;\n\nlocation = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location)\n+@"\Resources\batchfile.bat";\n\np.StartInfo.FileName = location;	0
11561432	11561323	Digitally signing an application that is compiled from source file?	ilmerge nonsigned.dll /keyfile:key.snk /out:signed.dll	0
7276199	7276158	skip lines that contain semi-colon in text file	var lines = File.ReadAllLines( path );\nforeach( var line in lines )\n{\n    if( line.StartsWith( ";" ) )\n    {\n        continue;\n    }\n    else\n    {\n        // do your stuff\n    }\n}	0
14636298	14633752	Format and Replace <TR> and <TD> within an ArrayList and get a formatted ArrayList	var regex = new System.Text.RegularExpressions.Regex(@"(?<=<td>).+?(?=</td>)", RegexOptions.Compiled | RegexOptions.IgnoreCase);\nvar text = "<tr> <td>FO Special Added (Comments, Part #, RFQ #) - 13, 13, 13</td> </tr><tr> <td>FO Special Added (Comments, Part #, RFQ #) - 14, 14, 14</td> </tr><tr> <td>FO Special Added (Comments, Part #, RFQ #) - 15, 15, 15</td> </tr> <td>FO Special Added (Comments, Part #, RFQ #) - 16, 16, 16</td> </tr>";\nvar matches = regex.Matches(text);\n\nvar results = matches.Cast<Match>()\n    .Select(match => match.Value)\n    .ToList();	0
12391510	12389491	CRUD operations in Datagridview bound to SQL Database	private void addButton_Click(object sender, System.EventArgs e)\n{\n    //I'm assuming your datatable is a member level variable \n    //otherwise you could get it through the grid\n    //have the datatable send you back a new row\n    DataRow newRow = table.NewRow();\n    //populate your new row with default data here\n    //....\n    //add the new row to the data table\n    table.Rows.Add(newRow);\n}	0
11367544	11367318	How do Windows services behave when entering/waking up from sleep or hibernate modes?	protected override bool OnPowerEvent(PowerBroadcastStatus powerStatus)\n  { \n     //do stuff here\n  }	0
31244897	31244722	C# Processes in a Listview?	void btnGetProcesses_Click(object sender, EventArgs e)\n{\n    Process[] processes = Process.GetProcesses();\n    ListViewItem lstViewItems = null;\n    foreach (Process process in processes)\n    {\n        lstViewItems = new ListViewItem();\n        lstViewItems.Text=process.Id.ToString();\n        lstViewItems.SubItems.Add(process.ProcessName);\n        lstViewItems.SubItems.Add(process.StartTime.ToString());\n        listView1.Items.Add(lstViewItems);\n    }\n}	0
15402709	15402677	How can I make it so that the EF updates my ModifiedDate on save?	System.Linq namespace	0
3209685	3208082	is there any way to get the index of an Item from a DataTable inside of a Repeater?	int resultIndex = (myRepeater.CurrentPageIndex * myRepeater.PageSize) + ItemIndex + 1	0
16224092	16109752	Send Email Async	System.Threading.Thread.Sleep(5000);	0
5372021	5370353	Select Rootnode from a WPF-TreeView	var treeViewItem = treeView.ItemContainerGenerator.ContainerFromIndex(0) as TreeViewItem;\n\ntreeViewItem.Focus();	0
29639144	28911162	What should you do if you have an interface with a collection of objects and you want both a read-only and a read-write version of the interface?	public interface IOptionSelector<T>\n{\n    event EventHandler SelectedOptionChanged;\n}\npublic interface IReadOnlyOptionSelector<T> : IOptionSelector<T>\n{\n    IReadOnlyCollection<T> Options { get; }\n}\npublic interface IWritableOptionsSelector<T> : IOptionSelector<T>\n{\n    ICollection<T> Options { get; }\n}	0
13623989	12200988	Array of custom object from .NET to VB6	[ComVisible(true)]	0
7968398	7968302	How do I put a panel of buttons into flow layout panel?	public class Form1\n{\n    private Panel CreateNotificationPanel()\n    {\n        var p = new Panel { BackColor = Color.Red };\n        p.Controls.Add(new Button { Text = "Test" });\n        return p;\n    }\n\n    private void Form1_Load(System.Object sender, System.EventArgs e)\n    {\n        var flp = new FlowLayoutPanel { Dock = DockStyle.Fill };\n\n        flp.Controls.Add(CreateNotificationPanel());\n        flp.Controls.Add(CreateNotificationPanel());\n        flp.Controls.Add(CreateNotificationPanel());\n\n        this.Controls.Add(flp);\n    }\n\n    public Form1() { Load += Form1_Load; }\n}	0
14058171	14057994	Linq two tables in to one	public void Linq102() \n{ \n\n    string[] categories = new string[]{  \n        "Beverages",   \n        "Condiments",   \n        "Vegetables",   \n        "Dairy Products",   \n        "Seafood" };  \n\n    List<Product> products = GetProductList(); \n\n    var q = \n        from c in categories \n        join p in products on c equals p.Category \n        select new { Category = c, p.ProductName }; \n\n    foreach (var v in q) \n    { \n        Console.WriteLine(v.ProductName + ": " + v.Category);  \n    } \n}	0
25119900	25119695	Convert string into mm/dd/yyyy format	string[] formats= {"dd/MM/yyyy", "dd-MMM-yyyy", "yyyy-MM-dd", \n                   "dd-MM-yyyy", "M/d/yyyy", "dd MMM yyyy"};\nstring converted = DateTime.ParseExact("16-05-2014", formats, CultureInfo.InvariantCulture, DateTimeStyles.None).ToString("MM/dd/yyyy");	0
5492848	5492673	How do can I get XmlRoot to have a collection of objects?	[XmlRoot("Farm")]\npublic class Farm\n{\n    [XmlElement("Person", typeof(Person))]\n    [XmlElement("Dog", typeof(Dog))]\n    public List<Animal> Items { get; set; }\n}	0
23098326	23098191	Failed to serialize the response in Web API with Json	public class UserModel {\n    public string Name {get;set;}\n    public string Age {get;set;}\n    // Other properties here that do not reference another UserModel class.\n}	0
115440	115399	Converting a year from 4 digit to 2 digit and back again in C#	DateTime expirationDate = new DateTime(2008, 1, 31); // random date\nstring lastTwoDigitsOfYear = expirationDate.ToString("yy");	0
13717524	13716186	how to cast variable data in wp7withC#?	private void g1_Hold(object sender, Microsoft.Phone.Controls.GestureEventArgs e)\n        {\n              StackPanel stk = (StackPanel)sender;\n              ClassName sg = (ClssName)stk.DataContext;\n              string path=sg.imagepath;\n        }	0
21933056	21932323	Find Index of Item in ItemsControl nested inside a LixtBox.Item	VisualTreeHelper.GetParent(myUserControl);	0
30206828	30206764	List To ObservableCollection	ObservableCollection<Product> ProductsObject = new ObservableCollection<Product>();\n\n for (int i = 0; i < GetProductByCategoryResultObject.Products.Count; i++)\n            {\n             ProductsObject.Add(GetProductByCategoryResultObject.Products[i]); \n            }\nProductListView.ItemsSource = ProductsObject;	0
3241485	3241465	How to marshal a struct into a UInt16 Array	Buffer.BlockCopy	0
25056262	25055091	C# code to find whether today Date lies between or equal to the two other specified date	DateTime dat1 = Convert.ToDateTime("7/28/2014");\n        DateTime dat2 = Convert.ToDateTime("8/1/2014");\n\n        DateTime today = Convert.ToDateTime(DateTime.Now.ToString("MM/dd/yyy"));\n\n        if (today > dat1 && today < dat2)\n        {\n\n           // between\n        }\n        else\n        {\n            // lies between\n        }	0
32134282	32128348	ITextSharp SetListSymbol as an image	Image image = Image.getInstance(IMG);\nimage.scaleAbsolute(12, 12);\nimage.setScaleToFitHeight(false);\nList list = new List();\nlist.setListSymbol(new Chunk(Image.getInstance(image), 0, 0));\nlist.add("Hello World");\nlist.add("This is a list item with a lot of text. It will certainly take more than one line. This shows that the list item is indented and that the image is used as bullet.");\nlist.add("This is a test");\ndocument.add(list);	0
20085621	20085569	Regex to validate a number for length and start digits	Regex rx = new Regex( @"^(?!9999)\d{5,9}$" ) ;	0
10257422	10226044	Can't change public variables on a script attached to a gameobject. Values are restored upon play	EditorUtility.SetDirty (tb);	0
9921237	9920804	How to list _all_ objects in Amazon S3 bucket?	static AmazonS3 client;\nclient = Amazon.AWSClientFactory.CreateAmazonS3Client(\n                    accessKeyID, secretAccessKeyID);\n\nListObjectsRequest request = new ListObjectsRequest();\nrequest.BucketName = bucketName;\ndo\n{\n   ListObjectsResponse response = client.ListObjects(request);\n\n   // Process response.\n   // ...\n\n   // If response is truncated, set the marker to get the next \n   // set of keys.\n   if (response.IsTruncated)\n   {\n        request.Marker = response.NextMarker;\n   }\n   else\n   {\n        request = null;\n   }\n} while (request != null);	0
32438520	32438291	How can I stop running application in backgournd and exit without exception?	var processes=Process.GetProcessByName( "AppName" );\nforeach(var process in processes )\n    process.Kill();	0
6411012	6410817	How do i Receive input which I put into my two dimensional array in c#?	int rows = 8;\nint colums = 8;\nString[,] data = new String[colums, rows];\nint x = 0;\nint y = 0;\n\nfor(; y < rows; y++)\n{\n    for (; x < colums; x++)\n    {\n        Console.Write(data[x, y] + " ");\n        if (x == (colums - 1))\n        {\n            Console.WriteLine("");\n            Console.WriteLine("");\n        }\n    }\n    x = 0;\n}\n\nint userSelectedHomeTeam\nint userSelectedAwayTeaM\n\nConsole.WriteLine("Select home team by the number")\nfor(int i = 1; i < colums; i++)\n{   \n    Console.WriteLine(data[i, 0] + " " + i)\n}\nstr = Console.ReadLine(); \nuserSelectedHomeTeam = Int32.Parse(str);\n\nConsole.WriteLine("Select away team by the number")\nfor(int i = 1; i < colums; i++)\n{   \n    Console.WriteLine(data[i, 0] + " " + i)\n}\nstr = Console.ReadLine(); \nuserSelectedAwayTeam = Int32.Parse(str);\n\nConsole.WriteLine("Write user input")\nstr = Console.ReadLine(); \ndata[userSelectedHomeTeam , userSelectedAwayTeam ] = str;	0
25152456	25152334	Paths in c# : WPF	var canvas = new Canvas\n             {\n                 Clip = Geometry.Parse("F1 M 0,0L 76,0L 76,76L 0,76L 0,0"),\n                 Margin = new Thickness(1330, 19, -231, 302)\n             };\n\nvar path = new Path\n           {\n               Width = 8,\n               Height = 8,\n               Fill = new SolidColorBrush(Colors.Black),\n               Stretch = Stretch.Fill,\n               Data = Geometry.Parse("F1 M 18,23L 58,23L 58,53L 18,53L 18,23 Z M 54,31L 22,31L 22,49L 54,49L 54,31 Z")\n           };\n\ncanvas.Children.Add(path);\nCanvas.SetTop(path, 3);\nCanvas.SetLeft(path, 3);	0
4207010	3719619	Create a designer-aware UserControl collection to be used runtime	public partial class DummyControlContainer : UserControl\n{\n    private Dictionary<string, Control> _ControlMap;\n\n    public DummyControlContainer()\n    {\n        InitializeComponent();\n\n        _ControlMap = new Dictionary<string, Control>();\n        this.ControlAdded +=\n            new ControlEventHandler(DummyControlCollection_ControlAdded);\n    }\n\n    void DummyControlCollection_ControlAdded(object sender,\n        ControlEventArgs args)\n    {\n        // If the added Control doesn't provide its own BindingContext,\n        // set a new one\n        if (args.Control.BindingContext == this.BindingContext)\n            args.Control.BindingContext = new BindingContext();\n        _ControlMap.Add(args.Control.Name, args.Control);\n    }\n\n    public Control this[string name]\n    {\n        get { return _ControlMap[name]; }\n    }\n}	0
12447824	12447776	Retrieve and Remove elements from string	List<string> lst = new List<string>(new string[] { "a", "b", "c", "d" });\nList<string> lst1 = lst.GetRange(0, 2);\nlst.RemoveRange(0, 2);	0
20412189	20411391	How to bind labels from AspxGridView?	protected void ASPxGridView1_CustomColumnDisplayText(object sender, \n   ASPxGridViewColumnDisplayTextEventArgs e)\n    {\n        if (e.Column.FieldName == "Column1")\n        {\n            Label1.Text = e.Value.ToString();\n        }\n\n        if (e.Column.FieldName == "Column2")\n        {\n\n            Label2.Text = e.Value.ToString();\n        }\n\n       . \n\n       .\n\n       if (e.Column.FieldName == "Column12")\n        {\n\n            Label12.Text = e.Value.ToString();\n        }\n\n    }	0
2809876	2809801	Insert line in xml doc	XmlNode XNode = doc.CreateProcessingInstruction("mso-application ", "progid=\"Excel.Sheet\"");\n     doc.AppendChild(XNode);	0
4492580	4492540	c# reading in a text file into datatable	static readonly char[] space = { ' ' };\n...\nstring[] items = line.Split(space, StringSplitOptions.RemoveEmptyEntries);	0
32249848	32245666	LINQ query from two related lists with specific criteria	Employees.SelectMany(e => e.ListEmployeeCashAllowances).Where(lc => lc.CashAllowanceId == selectedCashAllowanceId).Select(c => c.ValueTaken).Sum();	0
6296681	6296647	Determining which config file a setting originated from?	System.Configuration	0
29829324	29819605	How to find out if a directory itself is ReadOnly instead of underlying files	var writePermissionSet = new PermissionSet(PermissionState.None);\nwritePermissionSet.AddPermission(new FileIOPermission(FileIOPermissionAccess.Write, path));\n\nif (!Properties.Settings.Default.searchReadOnly &&\n    !writePermissionSet.IsSubsetOf(AppDomain.CurrentDomain.PermissionSet))\n    //diPath.Attributes.HasFlag(FileAttributes.ReadOnly))\n    searchable = false;	0
31641746	31596535	Player movement starts after a few seconds after pressing the button	anim.SetFloat(hash.speedFloat, 5.5f, speedDampTime, Time.deltaTime);	0
31900812	31900668	Casting/converting an expression back to a lambda of Func<Foo,bool> (after serialization)	var barkFunction = ((Expression<Func<Foo, bool>>)barkExpression).Compile()	0
34497794	34497717	How do I get rid of single quotes from a dataset?	tnParent.Text = dr["ACCT_GRP"].ToString().Replace("'"; "''");	0
3665026	3664747	Using Generics in a non-collection-like Class	public <Material> Material { get; }\npublic void Draw(<Tool> pen);	0
10037155	10036834	Set a range of bits in a circular bit field	long SetRangeMask(int lower, int upper)     // 3..7\n{\n   if (! (lower <= upper)) throw new ArgumentException("...");\n\n   int size = upper - lower + 1;            // 7 - 3 + 1 = 5\n   if (size >= 64) return -1;\n   long mask = (1 << size) - 1;             // #00100000 - 1  = #000011111\n   return mask << lower | mask >> -lower;   // #00011111 << 3 = #011111000\n}	0
15711032	15710763	Metro Apps: C#, read text file from internet	static async void Main()\n{\n    try \n    {\n      // Create a New HttpClient object.\n      HttpClient client = new HttpClient();\n\n      HttpResponseMessage response = await client.GetAsync("http://www.contoso.com/");\n      response.EnsureSuccessStatusCode();\n      string responseBody = await response.Content.ReadAsStringAsync();\n      // Above three lines can be replaced with new helper method in following line \n      // string body = await client.GetStringAsync(uri);\n\n      Console.WriteLine(responseBody);\n    }  \n    catch(HttpRequestException e)\n    {\n      Console.WriteLine("\nException Caught!"); \n      Console.WriteLine("Message :{0} ",e.Message);\n    }\n }	0
8976410	8967213	Strange Bug with WPF TabPage and Addin	private void TabHost_SelectionChanged(object sender, SelectionChangedEventArgs e)\n{\n    TabHost.Focus();\n}	0
25321259	25321224	Combining two LinQ queries	var dirs = from file in myList\n     let fileInfo = new DirectoryInfo(file)\n     orderby fileInfo.CreationTime ascending\n     select fileInfo;	0
27166203	27149666	OWIN + OAuth - How to provide User ID instead of UserName	var formCollection = (Microsoft.Owin.FormCollection)context.Parameters;\n\nvar userId = formCollection.Get("userId");	0
6039864	6036433	Datetime issues with Mongo and C#	public class MyClass {\n    public ObjectId Id;\n    [BsonRepresentation(BsonType.Document)]\n    public DateTime MyDateTime;\n}	0
9695944	9695818	What datetime format is a number like "22194885"?	>>> import time\n>>> time.localtime(22194885*60)\ntime.struct_time(tm_year=2012, tm_mon=3, tm_mday=13, tm_hour=19, tm_min=45, tm_sec=0, tm_wday=1, tm_yday=73, tm_isdst=1)	0
33872164	33871777	Get the text after specific word for substring c#	private static int Main(string[] args)\n{\n    string line= "<H2:H2LabelComboBoxCell ID=\"LabelComboboxCellProject\"  SecurityID=\"CD4D3959-0ADB-4375-8DCF-917157528BDE\"/>";\n\n    string stringToFind = "ID=\"";\n    int firstQuote = line.IndexOf(stringToFind) + stringToFind.Length;\n    int nextQuote  = line.IndexOf("\"",firstQuote);\n\n    string id= line.Substring(firstQuote,nextQuote-firstQuote);\n\n    System.Console.Write("id="+id);\n    return 0;\n}	0
2150316	2150245	Adding an Event to a "specific" Google Calender with GData API	Uri postUri = new Uri();	0
1626475	1626426	try finally mystery	static void Main(string[] args)\n{\n    int counter = 0;\n    Console.WriteLine(fun(ref counter)); // Prints 1\n    Console.WriteLine(counter); // Prints 3\n}        \n\nstatic int fun(ref int counter)\n{\n  try\n  {\n      counter = 1;\n      return counter;\n  }\n  finally\n  {\n      counter = 3;\n  }\n}	0
19002477	18825745	Get footer row cell values of gridview	protected void insertButton_Click(object sender, EventArgs e)\n{\n    // This is the crux - \n    GridViewRow row = (GridViewRow)((sender as Button).NamingContainer);\n    // ...\n    // then you can get your textboxes\n    // Since we know it's an insert\n    dt.Columns.Add("id");\n    dt.Columns.Add("name");\n    dt = (DataTable)Session["students"];\n    DataRow dr = dt.NewRow();\n    TextBox txtnewid = (TextBox) row.FindControl("txtNewId");\n    TextBox txtnewName =  (TextBox) row.FindControl("txtNewName");\n    dr["id"] =  txtnewid.Text;\n    dr["name"] = txtnewName.Text ;\n    dt.Rows.Add(dr);\n    Session["students"] = dt;\n    gv.DataSource = dt;\n    gv.DataBind();\n}	0
11123598	11123561	how to align buttons from left to right	int lastX = 0;\nfor (int i = 0; i < 4; i++) {\n  Button b = new Button();\n  b.Location = new Point(lastX, 0);\n  this.Controls.Add(b);\n  lastX += b.Width;\n}	0
12475083	12474818	Finding the maximum possible font size for multiple TextBlocks	private void MeasureStringWidth(PaintEventArgs e)\n{\n\n    // Set up string. \n    string measureString = "Measure String";\n    Font stringFont = new Font("Arial", 16);\n\n    // Set maximum width of string. \n    int stringWidth = 200;\n\n    // Measure string.\n    SizeF stringSize = new SizeF();\n    stringSize = e.Graphics.MeasureString(measureString, stringFont, stringWidth);\n\n    // Draw rectangle representing size of string.\n    e.Graphics.DrawRectangle(new Pen(Color.Red, 1), 0.0F, 0.0F, stringSize.Width, stringSize.Height);\n\n    // Draw string to screen.\n    e.Graphics.DrawString(measureString, stringFont, Brushes.Black, new PointF(0, 0));\n}	0
7604367	7211754	Copy subset of items from one RadComboBox to another	/// <summary>\n/// Prepares the range specifier.\n/// </summary>\nprivate void PrepareRangeSpecifier()\n{                  \n    //clear the items from the end range list\n    ddlEndDayOfWeek.Items.Clear();\n\n    if (pnlEndDayOfWeek.Visible)\n    {\n        foreach (RadComboBoxItem item in ddlStartDayOfWeek.Items)\n        {\n            //insert the list items from the start range list\n            if (item.Index > ddlStartDayOfWeek.SelectedIndex)\n                ddlEndDayOfWeek.Items.Add(new RadComboBoxItem(item.Text, item.Value));\n        }\n\n        //set end range panel visibility\n        pnlEndDayOfWeek.Visible = ddlEndDayOfWeek.Items.Count > 0;\n    }\n\n    //if the end range has any items\n    if (ddlEndDayOfWeek.Items.Count > 0)\n        ddlEndDayOfWeek.Items.FirstOrDefault().Selected = true;\n}	0
25427320	25426930	How can I set WPF window size is 25 percent of relative monitor screen	this.Height = (System.Windows.SystemParameters.PrimaryScreenHeight * 0.25);\nthis.Width = (System.Windows.SystemParameters.PrimaryScreenWidth * 0.25);	0
10804263	10804233	How to modify the previous line of console text?	Console.SetCursorPosition(0, Console.CursorTop -1);\nConsole.WriteLine("Over previous line!!!");	0
29769026	29768253	How to pass a string in the format <someText> in MailMessage.Body Property	MailMessage msg = new MailMessage();\nstring system_Area_Encoded = HttpContext.Current.Server.HtmlEncode(system_Area);\nstring assigned_ToVal_Encoded = HttpContext.Current.Server.HtmlEncode(Assigned_ToVal);\nstring taskStatus_Encoded = HttpContext.Current.Server.HtmlEncode(TaskStatus);\nstring msgBody_Encoded = HttpContext.Current.Server.HtmlEncode(MsgBody);\nmsg.Body = string.Format(@"<b>System Area :</b>{0}<br /><b>Assigned To : </b>{1}<br /><b>Status :</b><font color=#0000FF>{2}</font><br /><br><b>Description :</b> {3}", system_Area_Encoded, assigned_ToVal_Encoded, taskStatus_Encoded, msgBody_Encoded);	0
1825949	1825301	Using an (I)List<string> as the source for a DataColumn	List<string>	0
24057341	24054186	How to do a "Pointer to Pointer" in C#?	public class Node {\n  public Node next;\n  public int val;\n}\nclass MyList {\n  Node head = null;\n  Node tail = null;\n  public MyList() { }\n  bool isEmpty() {\n    return head == null;\n  }\n  void add(int val) {\n    if (isEmpty())\n      head = tail = new Node();\n    else {\n      tail.next = new Node();\n      tail = tail.next;\n    }\n    tail.val = val;\n  }\n}	0
6417403	6417380	How to reverse a LINQ to SQL query	var News = (from news in db.News                   \n               select new \n               {\n               ID = news.NewsID,\n               kort = news.Short\n               }).AsEnumerable().Reverse();	0
4927119	4883618	Empty array with BinaryReader on UploadedFile in c#	b.BaseStream.Position = 0;	0
14821797	14821710	Blank Screen on windows	using System.Runtime.InteropServices; //to DllImport\n\npublic int WM_SYSCOMMAND = 0x0112;\npublic int SC_MONITORPOWER = 0xF170; //Using the system pre-defined MSDN constants that can be used by the SendMessage() function .\n\n\n[DllImport("user32.dll")]\nprivate static extern int SendMessage(int hWnd, int hMsg, int wParam, int lParam);\n//To call a DLL function from C#, you must provide this declaration .\n\n\nprivate void button1_Click(object sender, System.EventArgs e)\n{\n\nSendMessage( this.Handle.ToInt32() , WM_SYSCOMMAND , SC_MONITORPOWER ,2 );//DLL function\n}	0
19664670	19664212	Regular Expression match based on string but do not select	(?<=[\r\n]SVC\*)\b(\w*)\b	0
34411888	34411767	Iterate over datatable and assign values to different variables	SomeClass.Range1 = (int)dt.Rows[0]["Range"]; //Gets value in 'Range' column in first row.\nSomeClass.Range2 = (int)dt.Rows[1]["Range"]; //Gets value in 'Range' column in second row.\n//Add more here.	0
9610000	9605826	Regular expression to remove link from image in html	HtmlDocument doc = new HtmlDocument();\ndoc.LoadHtml("text <a href=\"...\" class=\"...\"><img src=\"...\" class=\"...\" width=\"...\" /></a> more text"\n     +" <a href=\"...\" class=\"...\"><img src=\"...\" class=\"...\" width=\"...\" /></a> even more text\"");\n\nvar firstImage = doc.DocumentNode.Descendants("img").Where(node => node.ParentNode.Name == "a").FirstOrDefault();\n\nif (firstImage != null)\n{\n    var aNode = firstImage.ParentNode;\n    aNode.RemoveChild(firstImage);\n    aNode.ParentNode.ReplaceChild(firstImage, aNode);\n}\n\nvar fixedText = doc.DocumentNode.OuterHtml;\n//doc.Save(/* stream */);	0
25597742	25562712	How can I get rid of the namespace prefix from XElement like this (C#)?	public static void RemoveNamespace(this XElement element)\n    {\n        foreach (XElement e in element.DescendantsAndSelf())\n        {\n            if (e.Name.Namespace != XNamespace.None)\n                e.Name = e.Name.LocalName;\n\n            if (e.Attributes().Any(a => a.IsNamespaceDeclaration || a.Name.Namespace != XNamespace.None))\n                e.ReplaceAttributes(e.Attributes().Select(NoNamespaceAttribute));\n        }\n    }\n\n    private static XAttribute NoNamespaceAttribute(XAttribute attribute)\n    {\n        return attribute.IsNamespaceDeclaration\n            ? null\n            : attribute.Name.Namespace != XNamespace.None\n                ? new XAttribute(attribute.Name.LocalName, attribute.Value)\n                : attribute;\n    }	0
858750	858735	how to convert this line into vb.net	Return RedirectToAction("Details", New With { .id = dinner.DinnerID})	0
19291473	19115578	How to suppress global mouse click events from windows?	using System;\nusing System.Collections.Generic;\nusing System.ComponentModel;\nusing System.Data;\nusing System.Drawing;\nusing System.Linq;\nusing System.Text;\nusing System.Windows.Forms;\nusing System.Runtime.InteropServices;\n\nnamespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n\n[return: MarshalAs(UnmanagedType.Bool)]\n[DllImport("user32.dll", CharSet = CharSet.Auto, ExactSpelling = true)]\npublic static extern void BlockInput([In, MarshalAs(UnmanagedType.Bool)]bool fBlockIt);\n\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void Form1_Load(object sender, EventArgs e)\n        {\n            this.Show();\n            //Blocks the input\n            BlockInput(true);\n            System.Threading.Thread.Sleep(5000);\n            //Unblocks the input\n            BlockInput(false); \n        }\n    }\n}	0
1757493	1757439	Connecting to a MySQL database with C# express via ODBC	MySql.Data.MySqlClient.MySqlConnection conn;\nstring myConnectionString;\n\nmyConnectionString = "server=127.0.0.1;uid=root;pwd=12345;database=test;";\n\ntry\n{\n    conn = new MySql.Data.MySqlClient.MySqlConnection();\n    conn.ConnectionString = myConnectionString;\n    conn.Open();\n}\ncatch (MySql.Data.MySqlClient.MySqlException ex)\n{\n    MessageBox.Show(ex.Message);\n}	0
2354668	2354613	WPF MultiBindings	MultiBinding multiBinding = new MultiBinding();\n\nmultiBinding.Converter = converter;\n\nmultiBinding.Bindings.Add(new Binding\n{\n    ElementName = "FirstSlider",\n    Path = new PropertyPath("Value")\n});\nmultiBinding.Bindings.Add(new Binding\n{\n    ElementName = "SecondSlider",\n    Path = new PropertyPath("Value")\n});\nmultiBinding.Bindings.Add(new Binding\n{\n    ElementName = "ThirdSlider",\n    Path = new PropertyPath("Value")\n});	0
13117066	13116931	How to Edit/Update Data in Collection in C#	UserForms[0].Visibility = true;	0
30560926	30429487	How to read Text property of ScintillaNET class	private void FormClosing(object sender, FormClosingEventArgs e)\n{\n    CachedText = scintilla.Text;\n}\n\npublic string CachedText { get; private set; }	0
6075558	6056165	parse email with regex in c#	atext = ALPHA / DIGIT / ; Any character except controls,\n        "!" / "#" /     ;  SP, and specials.\n        "$" / "%" /     ;  Used for atoms\n        "&" / "'" /\n        "*" / "+" /\n        "-" / "/" /\n        "=" / "?" /\n        "^" / "_" /\n        "`" / "{" /\n        "|" / "}" /\n        "~"	0
17288479	17288293	Parsing through xml page with c#	class Program\n{\n    static void Main(string[] args)\n    {\n        var doc = new XmlDocument();\n        doc.Load(@"..\..\input.xml");\n\n        var container = doc.DocumentElement\n            .GetElementsByTagName("Dealers")\n            .OfType<XmlElement>()\n            .FirstOrDefault();\n\n        if (container == null) return;\n\n        var dealers = container\n            .GetElementsByTagName("Dealer")\n            .OfType<XmlElement>();\n\n        foreach (var dealer in dealers)\n        {\n            var dealerId = dealer.GetAttribute("id");\n            Console.Write(dealerId + " - ");\n\n            var descrip = dealer.GetElementsByTagName("Description").OfType<XmlElement>().FirstOrDefault();\n            if (descrip != null)\n                Console.WriteLine(descrip.InnerText);\n\n            // etc...\n        }\n        Console.ReadLine();\n    }\n}	0
31866494	31866322	How to correctly add day, hour and minute to existing date	int serviceday;\nint servicehour;\nint serviceminute;\nInt32.TryParse(ServiceDay, out serviceday);\nInt32.TryParse(ServiceHour, out servicehour);\nInt32.TryParse(ServiceMinute, out serviceminute);\nDateTime finalDateTime = serviceEntry.ServiceDateTime\n                        .AddDays(serviceday)\n                        .AddHours(servicehour)\n                        .AddMinutes(serviceminute);	0
11178009	11177893	C# How to get required control (ImageList) while iterating through contols on a Windows Form	foreach (Component comp in this.components.Components) {\n            var ilist = comp as ImageList;\n            if (ilist != null) {\n                // Got one, do something with it\n                //...\n            }\n        }	0
203289	203246	How can I keep a console open until CancelKeyPress event is fired?	class Program\n{\n\n    private static bool _s_stop = false;\n\n    public static void Main(string[] args)\n    {\n        Console.CancelKeyPress += new ConsoleCancelEventHandler(Console_CancelKeyPress);\n        while (!_s_stop)\n        {\n            /* put real logic here */\n            Console.WriteLine("still running at {0}", DateTime.Now);\n            Thread.Sleep(3000);\n        }\n        Console.WriteLine("Graceful shut down code here...");\n\n        //don't leave this...  demonstration purposes only...\n        Console.ReadLine();\n    }\n\n    static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e)\n    {\n        //you have 2 options here, leave e.Cancel set to false and just handle any\n        //graceful shutdown that you can while in here, or set a flag to notify the other\n        //thread at the next check that it's to shut down.  I'll do the 2nd option\n        e.Cancel = true;\n        _s_stop = true;\n        Console.WriteLine("CancelKeyPress fired...");\n    }\n\n}	0
4439999	4439949	How to achieve ImageAlign.MiddleCenter in the overriden OnPaint method	oDrawRectangle = new Rectangle(this.Width / 2 - iWidth / 2, this.Height / 2 - iHeight / 2, iWidth, iHeight);	0
23527112	23526973	How to hide items in combo-boxes?	if (variable == 1) {\n    ComboxBox1.Items.Add("item3");\n}	0
10084236	10084125	How do I show the Alert Box first and then redirect to any page with query strings?	ScriptManager.RegisterStartupScript(UpdatePanel2, this.GetType(), "click", "alert('This Email address is already registered...');window.location.href ='test.aspx?WidgetID=" + Request.QueryString["WidgetID"] + "&lan=" + readCookie() + "&seeHome=true'", true);	0
1804127	1803831	Is it possible to clone a ValueType?	public static void Main()\n{\n    List<ValueType> values = new List<ValueType> {3, DateTime.Now, 23.4M};\n    DuplicateLastItem(values);\n\n    Console.WriteLine(values[2]);\n    Console.WriteLine(values[3]);\n    values[3] = 20;\n    Console.WriteLine(values[2]);\n    Console.WriteLine(values[3]);\n}\n\nstatic void DuplicateLastItem(List<ValueType> values2)\n{\n    values2.Add(values2[values2.Count - 1]);\n}	0
15400469	15400421	Change button text after click, then change it back after clicking again	private void OrdersButton_Click(object sender, EventArgs e)\n    {\n        if (OrdersButton.Text == "Turn Orders On")\n        {\n            OrdersButton.Text = "Turn Orders Off";\n        }\n        else if (OrdersButton.Text == "Turn Orders Off")\n        {\n            OrdersButton.Text = "Turn Orders On";\n        }\n    }	0
30882526	30865773	Windows Service sends request twice within for loop	protected override void OnStart(string[] args)\n        {\n            this.timer = new System.Timers.Timer(10000D);\n            this.timer.AutoReset = true;\n            this.timer.Elapsed += new System.Timers.ElapsedEventHandler(this.timer_Elapsed);\n            this.timer.Start();\n        }\n        protected override void OnStop()\n        {\n            this.timer.Stop();\n            this.timer = null;\n        }\n\n        protected void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n        {\n            this.proccessQue();\n        }	0
19714212	19714145	Getting attributes from same-named XDocument elements using LINQ	XDocument doc = XDocument.Parse(xml);\nList<string> ids = doc.Descendants("employee")\n                        .Select(e => e.Attribute("id").Value)\n                          .ToList();	0
17174053	17174006	How to Put OR condition in Xpath using Html AGility Pack	htmlDoc.DocumentNode.SelectNodes("//div[@ispublished='false' or @ispublished='False']");	0
23741859	23740759	Array to Sort High Scores	int[] scoreArray = { 5, 3, 9, 8, 1 };\n\n        int new_number = 6;\n\n        //Replaces smallest number by your new number\n        int min_index = Array.IndexOf(scoreArray, scoreArray.Min());\n        scoreArray[min_index] = new_number;\n\n        Array.Sort(scoreArray);\n        Array.Reverse(scoreArray);	0
22786779	22775928	Get color Name from color class	string name = "Unknown";\n        foreach (KnownColor kc in Enum.GetValues(typeof(KnownColor)))\n        {\n            Color known = Color.FromKnownColor(kc);\n            if (Color.FromArgb(255,255,140,0).ToArgb() == known.ToArgb())\n            {\n                label1.Text = known.Name;\n                break;\n            }\n        }	0
30341301	30340599	How to get random records from a viewmodel	//List of items to return\nList<PlanObjectsViewModel> result = new List<PlanObjectsViewModel>();\n\nRandom rand = new Random();\nint temp=0;\n\nwhile(budget>temp)\n{\n    //Get random item within selection\n    int randi = rand.Next(0, count);\n    var nthItem = model1.Skip(randi).First();\n\n    //Remove this test if you are happy adding duplicates\n    if (!result.Find(nthItem)\n    {\n        result.Add(nthItem); \n\n        //Update temp with calculation from nthItem just added\n    }\n}	0
32853176	32853127	Trying to refine several if statements down	hitBounds = Math.Abs(ship.position.x - transform.position.x) >= xBound || Math.Abs(ship.position.y - transform.position.y) >= yBound;	0
10829659	10827433	Setting TextureAddressMode with HLSL	SamplerState somethingLikeThis {\n    Filter = MIN_MAG_MIP_LINEAR;\n    AddressU = Clamp;\n    AddressV = Clamp;\n};	0
10208665	10138181	Dynamically select tests to run with webdriver	[DynamicTestFactory]\n    public IEnumerable<Test> LoginAndOut() \n    {\n        string method;\n        while (Model.graphWalker.HasNextStep())\n        {\n            method=Model.graphWalker.GetNextStep().ToString();\n            if (method == string.Empty)\n                break;\n            yield return new TestCase(method, () =>\n                {\n                    object obj = this.GetType().InvokeMember(method, BindingFlags.InvokeMethod | BindingFlags.Instance | BindingFlags.Public, null, this, null);\n                });\n        }\n     }	0
29520433	29517673	How to use datacontract in C#?	namespace BH_Server {\n    [ServiceContract]\n    public interface BHInterface {\n        [OperationContract]\n        string GetName( string name );\n        [OperationContract]\n        Device GetDevice();\n    }\n    [DataContract( Name = "Device", Namespace = "" )]\n    public class Device {\n\n        [DataMember( Name = "SN", Order = 1 )]\n        public string SN { get; set; }\n    }\n}	0
16800239	16800146	Trying to replace a different amount of spaces with only one comma	Regex r = new Regex(@"[ ]{2,}");     \nvar newStr = r.Replace(FileContents, @",");	0
12322149	12322113	Implementing a button to do what file menu item does	ExportFile()	0
17277825	17277786	Get buttons by tag from a dictionary c#	buttons.Where(b => buttonGroups.ContainsKey((int)b.Tag))	0
32021662	32021644	Use LINQ instead of two for loops	foreach (var edge in distinctEdge)\n{\n    edge.value = EdgeList.Count(e => e.target == edge.target && e.source == edge.source);\n}	0
14749525	14748863	How can I use HtmlTextWriter to write html comments?	public static void WriteBeginComment(this HtmlTextWriter writer)\n{\n    writer.Write(HtmlTextWriter.TagLeftChar);\n    writer.Write("!--");\n}\n\npublic static void WriteEndComment(this HtmlTextWriter writer)\n{\n    writer.Write("--");\n    writer.Write(HtmlTextWriter.TagRightChar);\n}\n\npublic static void WriteComment(this HtmlTextWriter writer, string comment)\n{\n    if (\n        comment.StartsWith(">") || \n        comment.StartsWith("->") || \n        comment.Contains("--") ||\n        comment.EndsWith("-"))\n    {\n        throw new ArgumentException(\n            "text does not meet HTML5 specification",\n            "comment");\n    }\n\n    writer.WriteBeginComment();\n    writer.Write(comment);\n    writer.WriteEndComment();\n}	0
24026685	24025933	How do I remove my app from the task switcher on Windows Phone?	public MainPage()\n{\n    Windows.Phone.UI.Input.HardwareButtons.BackPressed += HardwareButtons_BackPressed;\n}\n\nprivate void HardwareButtons_BackPressed(object sender, Windows.Phone.UI.Input.BackPressedEventArgs e)\n{\n    /* When you don't know the namespace you can use this code instead of the lower\n\n    string[] Namespace = Frame.CurrentSourcePageType.FullName.Split('.');\n    if (!e.Handled && Frame.CurrentSourcePageType.FullName == Namespace[0] + ".MainPage")\n            Application.Current.Exit();\n    */\n    if (!e.Handled && Frame.CurrentSourcePageType.FullName == "NAMESPACE.MainPage")\n        Application.Current.Exit();\n}	0
9140460	9140417	C# - LINQToExcel - Null Values	Transaction_Id,Value_Date,Transmit_Date,Transmit_Time,Contract_Id,Contract_Amount,Contract_RageTestAmount,Employer_Code,Test_Acceptor,Institution_Id\n35454521,20111230,20120102,2:23:12,1442,1714.56,1,285.76,0,643650	0
32686746	32686731	c# - Advancing datetime (duration) from current date	protected void Button1_Click(object sender, EventArgs e)\n{    \n    DateTime dateToday = DateTime.Now;\n    DateTime dateInFiveDays = dateToday.AddDays(5);\n\n    lblDateToday = dateToday.ToString("MMMMMM dd, yyyy HH:mm");\n    lblValiDate = dateInFiveDays.ToString("MMMMMM dd, yyyy HH:mm");\n}	0
5948092	5947984	Inheritance of Attached Behaviors	property == null	0
8900860	8900294	Resharper is suggesting that string literals are localizable	Code Editing -> C# -> Localization	0
2673800	520910	How to simulate Windows shutdown for debugging?	rmtool.exe -p [PID] -S	0
32958858	32957898	Http Post a Stream in F# without reading into a Byte Array	let uploadFile (uri: Uri) fileName =\n    async {\n        use stream = File.OpenRead fileName\n        use client = new HttpClient()\n        return! client.PostAsync(uri, new StreamContent(stream)) |> Async.AwaitTask\n    }	0
13569334	13567488	loop through crystal sub reports using craxdrt	CRAXDDRT.SubreportObject subReport = null;\n\nforeach (CRAXDDRT.Section section in crystalReport.Sections)\n{\n    foreach (object item in section.ReportObjects)\n    {\n        subReport = item as CRAXDDRT.SubreportObject;\n        if (subReport != null)\n        {\n            //loop code here\n        }\n    }\n}	0
16791160	16521151	Saving a bitmap in emf format using memory stream	image.Save(Server.MapPath(FileName));\n        MemoryStream stream1 = new MemoryStream(System.IO.File.ReadAllBytes(Server.MapPath(Filename)));\n        System.IO.File.Delete(Server.MapPath(Filename));	0
8427120	8425146	Remove need of creating backup file while importing Excel spreadsheet to SQL Server database	File.Delete("<your file directory>");	0
25565417	25565226	Multiple constructors of length 2. Unable to disambiguate with Unity	public class MyMongoRepository<T> : MongoRepository<T>\n{\n    // of course you should fill in the real connection string here.\n    public MyMongoRepository() : base("connectionString", "name") { }\n}\n\ncontainer.RegisterType(typeof(IRepository<>), typeof(MyMongoRepository<>));	0
10214900	10214848	How do I convert this double foreach loop to just lambdas?	int numOfEvents = eventsForAllMonths.SelectMany(m => m.AllDays)\n                                    .Select(d => d.CalEvents.Count)\n                                    .Sum();	0
11871054	11868939	Need method to return XElement instead of byte[]	result = kpiReportClient.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);\nConsole.WriteLine(result);\nresult = kpiReportClient.Render(format, devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);\nStream resStream = new MemoryStream(result);\nvar nonRepSickReportForNM = XElement.Load(resStream);\nreturn nonRepSickReportForNM	0
21573609	21573221	How to assign date at each insertion in sql server c#	Table Leave\nemp_id,\nleave_id,\nleave_Type,\ndays_applied,\nfrom_date,\nto_date,\ndate_applied\n\n\nTable Leave Type\nleave_Type_id,\nleave_Type	0
1922253	1922199	C# Convert string from UTF-8 to ISO-8859-1 (Latin1) H	Encoding iso = Encoding.GetEncoding("ISO-8859-1");\nEncoding utf8 = Encoding.UTF8;\nbyte[] utfBytes = utf8.GetBytes(Message);\nbyte[] isoBytes = Encoding.Convert(utf8, iso, utfBytes);\nstring msg = iso.GetString(isoBytes);	0
19359937	19359862	Simulating behavior of arrow up/ down keys on a tree view with the help of two buttons in wpf	private void button1_Click(object sender, EventArgs e)\n    {\n        treeView1.Focus();\n        SendKeys.SendWait("{UP}");\n    }	0
11452095	11446144	Sending a windows form value to a wpf control to update a property located in the wpf control.	WPFUC userControl = (WPFUC)elementHost1.Child;\nuserControl.Parameter = "line"; //To draw line\nor\nuserControl.Parameter = "rectangle"; //To draw rectangle	0
14746264	14744455	How to convert WAV stream to MP3 using Naudio?	MediaFoundationEncoder.EncodeToMp3	0
19974362	19955853	Devexpress Reporting get Row data by click in it	private void xrLabel_BeforePrint(object sender, System.Drawing.Printing.PrintEventArgs e) {\n    // Obtain the current label.\n    XRLabel label = (XRLabel)sender;\n\n    //Obtain the parent Report\n    XtraReportBase parentReport = label.Report;\n\n    //Get the data object\n    object currentData = parentReport.GetCurrentRow();\n\n    //Pass this object to Tag\n    label.Tag = currentData;\n}	0
27264054	27207336	DataGridView with Enums only sets default value in BindingList	private void DataGridView_CellValueChanged(object sender, DataGridViewCellEventArgs e)\n{\n      this.bindingList[e.RowIndex] = (myEnumeration)DataGridView[e.ColumnIndex, e.RowIndex].Value;\n}	0
10783742	10782406	Sending mail through automation (c # ) [mail with attachement]	using System.Net;\nusing System.Net.Mail;\n\nvar fromAddress = new MailAddress("from@gmail.com", "From Name");\nvar toAddress = new MailAddress("to@example.com", "To Name");\nstring fromPassword = "fromPassword";\nstring subject = "Subject";\nstring body = "Body";\n\nvar smtp = new SmtpClient\n           {\n               Host = "smtp.gmail.com",\n               Port = 587,\n               EnableSsl = true,\n               DeliveryMethod = SmtpDeliveryMethod.Network,\n               UseDefaultCredentials = false,\n               Credentials = new NetworkCredential(fromAddress.Address, fromPassword)\n           };\nusing (var message = new MailMessage(fromAddress, toAddress)\n                     {\n                         Subject = subject,\n                         Body = body\n                     })\n{\n    smtp.Send(message);\n}	0
2031290	2030614	Action Parameter Naming	public ActionResult ByAlias([Bind(Prefix = "id")] string alias) {\n    // your code here\n}	0
16153406	16152832	Call Method From BackgroundWorker	private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e) {\n        string path = (string)e.Argument;\n        processFile(path);\n    }\n\n    private void processToolStripMenuItem_Click(object sender, EventArgs e) {\n        backgroundWorker1.RunWorkerAsync(openSingleFile.FileName);\n        processToolStripMenuItem.Enabled = false;\n    }\n\n    private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e) {\n        processToolStripMenuItem.Enabled = true;\n    }	0
9744152	9735140	How to generate a list of fakes using Moq	int numberOfElements = 10;\nvar mock = Mock.Of<ICalendar>(x =>\n           x.GetSchedules() == Enumerable.Repeat(Mock.Of<ISchedule>(), numberOfElements).ToList());	0
27894048	27893748	Maintain a responsive user interface with backgroundWorker and heavy animation	private static object _lock = new object();\nprivate static int _queuedCount = 0;\n\npublic Map()\n{\n  InitializeComponent();\n\n  _worker = new BackgroundWorker();\n  _worker.DoWork += _worker_DoWork;\n  _worker.ProgressChanged += _worker_ProgressChanged;\n  _worker.WorkerReportsProgress = true;\n}\n\nprivate void _worker_DoWork(object sender, DoWorkEventArgs e)\n{\n    _frameCount = _frames.FrameCount();\n    // For this specific example, _frameCount may be around 30000-40000\n    for (var i = 0; i < _frameCount; i++)\n    {\n      var f = _frames.Frame(i + 1);\n      lock(_lock)\n      {\n          _queuedCount++;\n      }\n      _worker.ReportProgress(i, f);\n      Thread.Sleep(_tickCount);\n      _suspend.WaitOne(); // Used to Pause the playback\n    }\n}\nvoid _worker_ProgressChanged(object sender, ProgressChangedEventArgs e)\n{\n  if (_queuedCount > 1)\n      //now queue is building up\n\n  this.Refresh();\n  lock(_lock)\n  {\n      _queuedCount--;\n  }\n}	0
27223636	27221037	Angular/Breeze SPA loading local data from webAPI service to unmapped entity	metadataStore.setEntityTypeForResourceName("Products", "Product:#Model");\nmetadataStore.setEntityTypeForResourceName("Uoms", "Uom:#Model");	0
2383354	2373298	How display encrypted image using BitmapImage	BitmapImage bi = new BitmapImage();\nbi.BeginInit();\nbi.CacheOption = BitmapCacheOption.OnLoad;\nbi.CreateOptions = BitmapCreateOptions.None;\nbi.StreamSource = decryptedImageStream;\nbi.EndInit();	0
23121713	23121333	How to insert an SQL literal as a query parameter in Dapper?	Connection.Query()	0
17154034	17153942	How to close command prompt on keyboard key down	Console.ReadKey();	0
19117216	19116996	C# htmlelement combined with variable	var elem = (HtmlTableCell)FindControl("cell_" + i.ToString());\nelem.InnerText = "yada yada";	0
6561589	6561546	Passing jQuery Selectors to a function Server side	var sel = eval(Selector);	0
25553495	25552944	WPF share string between 2 viewmodels	Text = "{Binding Path=Settings.TotalTime}"	0
31539263	31537840	Deserialize xml xmpp message to object	public class Forwarded\n{\n    [XmlElement(ElementName = "delay", Namespace = "urn:xmpp:delay")]\n    public Delay Delay { get; set; }\n    [XmlElement(ElementName = "message")]\n    public XmppMessage Message { get; set; }\n    [XmlAttribute(AttributeName = "xmlns")]\n    public string Xmlns { get; set; }\n}\n\npublic class Result\n{\n    [XmlElement(ElementName = "forwarded", Namespace = "urn:xmpp:forward:0")]\n    public Forwarded Forwarded { get; set; }\n    [XmlAttribute(AttributeName = "xmlns")]\n    public string Xmlns { get; set; }\n    [XmlAttribute(AttributeName = "id")]\n    public string Id { get; set; }\n}\n\n[XmlRoot(ElementName = "message")]\npublic class MessageHistory\n{\n    [XmlElement(ElementName = "result", Namespace = "urn:xmpp:mam:tmp")]\n    public Result Result { get; set; }\n    [XmlAttribute(AttributeName = "from")]\n    public string From { get; set; }\n    [XmlAttribute(AttributeName = "to")]\n    public string To { get; set; }\n}	0
2148350	2148309	How do I reference a field in Linq based on a dynamic fieldname	somevalue = typeof(MyTable).GetProperty(fieldName).GetValue(table, null);	0
30638688	30638597	Convert color to RRRGGGBBB	Byte[] SeatL1 = new UTF8Encoding(true)\n           .GetBytes("L1=" + r2.BackColor.R.ToString("000") + \n                     ", " + r2.BackColor.G.ToString("000") + \n                     ", " + r2.BackColor.B.ToString("000"));\nfsNew.Write(SeatL1, 0, SeatL1.Length);	0
18601706	18601430	Check the type of file clicked in a listbox	FileInfo finfo = new FileInfo(fileName);\nstring fileName = finfo.Extension	0
10028072	10028031	How to count lists inside another list List<List<KeyValuePair<string, double>>>	List<List<KeyValuePair<string, double>>> dblWordFreqByCluster = new List<List<KeyValuePair<string, double>>>();\n int count = dblWordFreqByCluster.count;	0
3207819	3207806	How can I get StackOverflow style timestamps with the DateTime class?	string str = DateTime.Now.ToString("u");	0
10049417	10049162	Use a variable DataFormatString in asp.net ascx	((BoundField)GridView1.Columns[ColumnIndex]).DataFormatString = myFormatString;	0
34476746	34476707	Loop through sequential control names C#	var nuds = new []\n{\n    numericUpDown1, numericUpDown2,\n    numericUpDown3, numericUpDown4,\n    numericUpDown5, numericUpDown6,\n    // etc\n};\n\nfor (int i = 0; i < readBuf.Length; i++)\n{\n    nuds[i].Value = Convert.ToDecimal(BitConverter.ToSingle(readBuf[i], startIndex: 0));\n}	0
15878640	15873352	Registering a SecurityTokenReceived Event Handler	FederatedAuthentication.SessionAuthenticationModule.SessionSecurityTokenReceived += SessionAuthenticationModule_SessionSecurityTokenReceived;	0
5212381	5212315	how to abort thread	Thread newThread = new Thread(delegate() { stream(string); });\nthis.list.Add(newThread);\nnewThread.isBackground = true;\nnewThread.Start();	0
6277931	6277653	how to set a column in gridview as hyperlink which is autogenerated	void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n    if (e.Row.RowType == DataControlRowType.DataRow)\n    {\n        var firstCell = e.Row.Cells[0];\n        firstCell.Controls.Clear();\n        firstCell.Controls.Add(new HyperLink { NavigateUrl = firstCell.Text, Text = firstCell.Text });\n    }\n}	0
17620128	17619709	How to binding Image from view-model in another dll?	new BitmapImage(new Uri("/vm;component/h.png", UriKind.RelativeOrAbsolute));	0
988928	988693	How can I update a TextBox from a class using events?	public class BusinessModel : INotifyPropertyChanged\n{\n    public event PropertyChangedEventHandler PropertyChanged;\n\n    private int _quantity;\n    public int Quantity\n    {\n        get { return _quantity; }\n        set \n        { \n            _quantity = value;\n            this.OnPropertyChanged("Quantity");            \n        }\n    }\n\n    void OnPropertyChanged(string PropertyName)\n    {\n        if (this.PropertyChanged != null)\n        {\n            this.PropertyChanged(this, new PropertyChangedEventArgs(PropertyName));\n        }\n    }\n }	0
19793718	19793675	Posting separate lines from TextAreaFor into separate DB rows	[HttpPost]\npublic ActionResult Create(Names name)\n{\n    var names = name.Split(new[] { '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries)\n    foreach(var n in names) \n    {\n        unitofwork.Names.Insert(n);\n    }\n\n    unitofwork.save();\n\n    return RedirectToAction("Index");\n}	0
32579308	32238286	Run Background Task at specific time - Windows 10 App	var tommorowMidnight = DateTime.Today.AddDays(1);\nvar timeTilMidnight = tommorowMidnight - DateTime.Now;\nvar minutesTilMidnight = (uint)timeTilMidnight.TotalMinutes;\nbuilder.SetTrigger(new TimeTrigger(minutesTilMidnight, true));	0
17107512	17107182	Windows 8 C# - retrieve a webpage source as string	public async Task<string> MakeWebRequest(string url)\n{\n    HttpClient http = new System.Net.Http.HttpClient();\n    HttpResponseMessage response = await http.GetAsync(url);\n    return await response.Content.ReadAsStringAsync();\n}	0
10554083	10553982	Remove white space from part of a string	var input = "SMS \r\n\t?    Map - locations of";\n\nvar regexPattern = @"(?<=?)\s+(?=\w)";\nvar cleanedInput = Regex.Replace(input, regexPattern, String.Empty);	0
6928406	6928281	Convert serialized C# DateTime to JS Date object	var src = "/Date(1302589032000+0400)/";\n\n//Remove all non-numeric (except the plus)\nsrc = src.replace(/[^0-9 +]/g, ''); \n\n//Create date\nvar myDate = new Date(parseInt(src));	0
7804149	7804121	Regex : Replace URL unless starts with src=	(?<!src=['"]?)(http|ftp|https):...	0
8385017	8384873	Open the DPI settings dialog programatically?	%windir%\system32\DpiScaling.exe	0
8158910	8158725	Randomly pick 4 elements from an array using c#	string[] addetailsID = new string[20];  // this is the array I want to index into\n        // generate the 4 unique indices into addetailsID\n        Random random = new Random();\n        List<int> indices = new List<int>();\n        while (indices.Count < 4)\n        {\n            int index = random.Next(0, addetailsID.Length);\n            if (indices.Count == 0 || !indices.Contains(index))\n            {\n                indices.Add(index);\n            }\n        }\n        // now get the 4 random values of interest\n        string[] strAdDetailsID = new string[4];\n        for (int i = 0; i < indices.Count; i++)\n        {\n            int randomIndex = indices[i];\n            strAdDetailsID[i] = addetailsID[randomIndex];\n        }	0
2281704	2280948	Reading data metadata from JPEG, XMP or EXIF in C#	public string GetDate(FileInfo f)\n    {\n        FileStream fs = new FileStream(f.FullName, FileMode.Open, FileAccess.Read, FileShare.Read);\n        BitmapSource img = BitmapFrame.Create(fs);\n        BitmapMetadata md = (BitmapMetadata)img.Metadata;\n        string date = md.DateTaken;\n        Console.WriteLine(date);\n        return date;\n    }	0
18551018	18550974	Having trouble calling a method from inside another method	Console.Writeline(RandomMessage());	0
9688359	9688019	setting javascript value from backend code	gts.push(['google_base_offer_id', document.getElementById('<%= hidden.ClientID %>').value]);	0
5320905	5314281	SQL Query DataTime value Inserting twice into the table	using (SqlCommand cmd = new SqlCommand(query, conn))\n        {\n          int 123;\n\n          cmd.Parameters.Add(new SqlParameter(@"Number", SqlDbType.int)).Value = 123;\n          cmd.Parameters.Add(new SqlParameter(@"aDateTime", SqlDbType.DateTime)).Value = mydate;\ncmd.Parameters.Add(new SqlParameter(@"aDateTime", SqlDbType.decimal)).Value = value;\n          cmd.ExecuteNonQuery();\n        }	0
28672593	28672364	How do I get a value from a Textbox, put it in a string, and when i click 2 buttons, it shows (kinda like a global?) C#	public partial class Form1 : Form\n{\n    public Form1()\n    {\n        InitializeComponent();\n    }\n\n    // Will return string on textBox1 uppon calling\n     private string ab(){\n       return textBox1.Text;\n    }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        MessageBox.Show(ab());\n    }     \n    private void button2_Click(object sender, EventArgs e)\n    {\n        MessageBox.Show(ab()+" Hello");\n    }\n}	0
25435389	25435314	how to get a excel cell values to variables in c# coded step	var value = demoWorksheet.get_Range("A1", "A1").Value2;	0
17321596	17321251	Replace every other of a certain char in a string	public static string[] StringToArray(string str)\n{\n    return str.Replace(" ", ",").Split(',');\n}\n\npublic static string ArrayToString(string[] array)\n{\n    StringBuilder sb = new StringBuilder();\n    for (int i = 0; i <= array.Length-1; i++)\n    {\n        sb.AppendFormat(i % 2 != 0 ? "{0} " : "{0},", array[i]);\n    }\n    return sb.ToString();\n}	0
16307733	16177729	Select row of unbound datagridview populated by query	private void dgvBRT_DoubleClick(object sender, EventArgs e)\n        {\n\n         if (dgvBRT.SelectedCells.Count > 0)\n            {\n             int selectedrowindex = dgvBRT.SelectedCells[0].RowIndex;\n\n             DataGridViewRow selectedRow = dgvBRT.Rows[selectedrowindex];\n\n             string BRTNumber = Convert.ToString(selectedRow.Cells["BRTNumber"].Value);  \n             // Open selected row\n\n              frmBRTDetail BRTDetail = new frmBRTDetail(this);\n              BRTDetail.LoadBRTNumberKey(BRTNumber, null);\n              BRTDetail.Show();\n            }\n        }	0
20765486	20764223	How to make a one to many and many to many listbox connection in C# asp.net webform?	ListItem newItem = null;\n    foreach (ListItem item in ListBox1.Items)\n    {\n        if (item.Selected)\n        {\n            foreach (ListItem innerItem in ListBox2.Items)\n            {\n                if (innerItem.Selected)\n                {\n                    newItem = new ListItem();\n                    newItem.Text = item.Text + innerItem.Text;\n                    ListBoxResult.Items.Add(newItem);\n                }\n            }\n        }\n    }	0
14565577	14565352	Compare a time difference with a fixed period	String recordTime = fileName.Split('_','-').Last();// format is 'yyyyMMddHHmmss'\nDateTime recordDateTime = DateTime.ParseExact( recordTime , "yyyyMMddHHmmss", CultureInfo.InvariantCulture );\n\nif ( recordDateTime.AddYears(2) < DateTime.Now )\n{\n    Console.WriteLine(fileName);\n}	0
10059311	10059063	How to pass a Lambda Expression as method parameter with EF	public TValue RetryHelper<T, TValue>(Func<ObjectSet<T>, TValue> func)\n    where T : class\n{\n    using (MyEntities dataModel = new MyEntities())\n    {\n        var entitySet = dataModel.CreateObjectSet<T>();\n        return FancyRetryLogic(() =>\n               {\n                   return func(entitySet);\n               });\n    }\n}\n\npublic User GetUser(String userEmail)\n{\n    return RetryHelper<User, User>(u => u.FirstOrDefault(x => x.UserEmail == userEmail));\n}	0
2198295	2198265	Linq to SQL: How can I update a formview that has data from multiple tables?	from c in db.Customer\njoin a in db.Account\non a.customerID equals c.customerID\nselect new Model {FirstName = c.firstName,LastName = c.lastName,Address = c.address,AccountRate = a.accountRate}	0
276650	276642	C#: Is there a shortcut to detect if mouse is still hovering on top of Label on MouseHover event?	private void label1_MouseHover(object sender, EventArgs e)\n    {\n        //make changes for hovering\n    }\n\n    private void label1_MouseLeave(object sender, EventArgs e)\n    {\n        //undo changes\n    }	0
2095790	2095166	Mapping a property to an SQL expression or multiple columns in Fluent nHibernate	Map(x => x.TransactionDate).Formula("[[sql statement]]");	0
12591981	12591945	Reading values from xml document	XmlNode root = doc.SelectSingleNode("/cXML");\nstring attrVal = root.Attributes["payloadID"].Value;	0
15072650	15072552	Use scientific notation only if needed	double number;\n\nnumber = .0023;\nConsole.WriteLine(number.ToString("G", CultureInfo.InvariantCulture));\n// Displays 0.0023\n\nnumber = 1234;\nConsole.WriteLine(number.ToString("G2", CultureInfo.InvariantCulture));\n// Displays 1.2E+03\n\nnumber = Math.PI;\nConsole.WriteLine(number.ToString("G5", CultureInfo.InvariantCulture));\n// Displays 3.1416	0
5297990	5297909	Why Mysql not give me my connectionstring back with password when I open the connection with constring who have password;	Persist Security Info=True	0
12739327	12726278	Change in converted time using TimeZone	DateTime indianStd = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "India Standard Time");\n\n   DateTime MyanmarStd = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "Myanmar Standard Time");\n\nDateTime SEAsia = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow, "SE Asia Standard Time");\n\n DateTime ConvertedDt = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(MyanmarStd, "Myanmar Standard Time", "India Standard Time");	0
19228873	19228821	Converting XML To dictionary	XElement root = XElement.Parse(strSerializedoutput);\nDictionary<int, Pair> list = root.Descendants("item")\n                                 .ToDictionary(x => (int) x.Attribute("id"),\n                                  x => {\n                            var pId = x.Parent.Attribute("id");\n                            var depthLevel = x.Attribute("level");\n                            return pId == null ? new Pair { parentID = 0, level = (int)depthLevel } :\n                            new Pair { parentID = (int)pId, level = (int)depthLevel };\n                          });\n\npublic class Pair\n{\n    public int parentID;\n    public int level;\n}	0
15584285	15583626	Opening a second PdfReader within a using block in iTextSharp	using (PdfReader reader = new PdfReader(FilePath),PdfReader reader1 = new PdfReader(MapFilePath))\n{\npass that reader1 object to AddMap method.\n}	0
12105352	12105309	Is there any logging of CoolStorage for MonoTouch activity?	var docFolder = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);\n\nCSConfig.Logging = true;\nCSConfig.LogFileName = Path.Combine(docFolder,"coolstorage.log");	0
27593620	27593522	overcoming gmails attachment blocking	private static void Main(string[] args)\n    {\n        var encodedString = System.IO.File.ReadAllText(@"D:\original.txt");\n        var bytes = System.Convert.FromBase64String(encodedString);\n        System.IO.File.WriteAllBytes("d:\\result.rar", bytes);\n    }	0
23132332	23103061	Looping through WPF Grid	foreach (DataTable table in result.Tables)\n    {\n        GfoTopBox box1 = StuffData(table);\n        Grid.SetRow(box1, j);\n        Grid.SetColumn(box1, i);\n        output.Children.Add(box1);\n\n        i++;\n        if (i >= output.ColumnDefinitions.Count)\n        {\n            i = 0;\n            j++;\n        }\n    }	0
4244676	4244642	Get Controls from a DataTemplate inside a ListBox (or Panorama)	FeedsPanorama.ItemContainerGenerator.ContainerFromItem(currentDataObject);	0
1478905	1478892	How to dynamically switch between comparing Less Than, Greater Than, or Equal To?	int value = int.Parse(txtByteValue.Text);\nint len = fi[i].Length;\n\nswitch (cmboCompareType.SelectedText)\n{\n    case "Greater Than": fileOK = len > value; break;\n    case "Less Than": fileOK = len < value; break;\n    case "Equal To": fileOK = len == value; break;\n}	0
19775214	19775172	Verify that a user is logged in using .Net	if(Membership.ValidateUser(username,password))\n{\n     FormsAuthentication.SetAuthCookie(username,true); \n} //do it in login page	0
20006982	20006631	How To Play Video in Windows Store App	MyMediaPlayer.Source = new Uri(_videos.Video[1].videourl3)	0
19187848	19187748	retrieving a salt from database	public string getSalt()\n{\n    string sql = "select DISTINCT Salt from Logins where Name = @username"; \n\n    using (var connection = new SqlConnection(@"server=.\SQLEXPRESS; database=loginsTest;Trusted_Connection=yes")) \n    using (var command = new SqlCommand(sql, connection))\n    {\n        //guessing at the column length here. Use actual column size instead of 20\n        command.Parameters.Add("@username", SqlDbType.NVarChar, 20).Value = userNameBox.Text;\n\n        connection.Open();\n        return (command.ExecuteScalar() as string) ?? "Error";\n    }\n}	0
17973782	17973578	How to Share My News on Facebook on Windows Phone 8	private void Button_Click(object sender, RoutedEventArgs e)\n{\n   //theMessageStatus is the message you want to post to FB/Twitter\n   ShareNewsArticle(theMessageStatus);\n}\n\nprivate void ShareNewsArticle(string message)\n{\n   ShareStatusTask sst = new ShareStatusTask();\n   sst.Status = message;\n   sst.Show();\n}	0
13722087	13722014	Insert 2 million rows into SQL Server quickly	// connect to SQL\nusing (SqlConnection connection = \n        new SqlConnection(connString))\n{\n    // make sure to enable triggers\n    // more on triggers in next post\n    SqlBulkCopy bulkCopy = \n        new SqlBulkCopy\n        (\n        connection, \n        SqlBulkCopyOptions.TableLock | \n        SqlBulkCopyOptions.FireTriggers | \n        SqlBulkCopyOptions.UseInternalTransaction,\n        null\n        );\n\n    // set the destination table name\n    bulkCopy.DestinationTableName = this.tableName;\n    connection.Open();\n\n    // write the data in the "dataTable"\n    bulkCopy.WriteToServer(dataTable);\n    connection.Close();\n}\n// reset\nthis.dataTable.Clear();	0
21775927	21775545	Do subtraction of last two rows of gridview using c#.net	DataColumn totalColumn = new DataColumn();\ntotalColumn.ColumnName = "FinalTotal";\ntotalColumn.DataType = typeof (int);\ntotalColumn.DefaultValue = 0;\ndtSourceTable.Columns.Add(totalColumn);\n\nforeach (DataRow row in dtSourceTable.Rows)\n{\n    row["FinalTotal"] = Convert.ToInt32\n       (row["HeadCount"]) - Convert.ToInt32(row["Total"]);\n}	0
26381481	26380796	How to automatically select a dropdownlist item based on the item's Text?	ddlType.SelectedValue = ddlType.Items.FindByText(dr1[0].ToString()).Value;	0
11496708	11496570	Hi, How to parse xml with descendants within descendants C#	XDocument streamFeed = XDocument.Load(new StringReader(response.Content));\nvar query =\n    from sticker in streamFeed.Root.Elements("sticker")\n    let imageData = sticker.Element("imageData")\n    select new Stickers\n    {\n        name = (string)sticker.Element("name"),\n        description = (string)sticker.Element("description"),   \n        image = (string)imageData.Element("baseImageUrl") + "huge" + (string)imageData.Element("imageUrlSuffix")\n    };\n\nstickersListBox.ItemsSource = query;	0
21542004	21541788	I can not use the properties and variables of a library of classes within a dll	libreriaCobol lc = new libreriaCobol();\nlc.property = "";  // here.	0
3784789	3784752	How to set the CTRL + R in Windows button	private void button1_KeyDown(object sender, KeyEventArgs e)\n        {\n            if (e.Modifiers == Keys.Control && e.KeyCode == Keys.R)\n            {\n            }\n\n        }	0
18615892	18615535	find most occurrences in linq to sql c#	var mostCommon = gradeData.GroupBy(x => x.TotalPoints)\n    .OrderByDescending(g => g.Count())\n    .Select(g => g.Key)\n    .First();	0
29038396	29037499	How would I access a random item from this list?	Random Rnd = new Random();\nvar jobItem = haggleList.ElementAt(Rnd.Next(1, haggleList.Count()));\nvar selectedJobId = Convert.ToInt32(jobItem.JobId);	0
3591016	3590749	Convert ColorConvertedBitmap to byte array in C#	public static byte[] BitmapToBytes(ColorConvertedBitmap ccb)\n{\n    byte[] bytes = new byte[ccb.PixelWidth * ccb.PixelHeight * ccb.Format.BitsPerPixel / 8];\n    ccb.CopyPixels(bytes, ccb.PixelWidth * ccb.Format.BitsPerPixel / 8, 0);\n    return bytes;\n}	0
27487852	27487264	Implementing & Displaying UI Timer with WPF MVVM	TimeElapsed = String.Format("{0:00}:{1:00}:{2:00}", total.Hours, total.Minutes, total.Seconds / 10);	0
5004579	5004481	LINQ: Remove Element fron XML based on attribute value?	xdoc.XPathSelectElement("Projects/Project[@projectName = 'project1']").Remove();	0
20303071	20302944	How to reference a control in Asp.Net C# for a textbox, dropdownlist, etc	DropDownList ddl =  (DropDownList)LoginView1.FindControl("ddlName");\n ddl.DataSource = connDr;       ?    \n        ddl.DataValueField = DataPara; ?        \n        ddl.DataTextField = DataPara;  ?            \n        ddl.DataBind();	0
2861491	2861470	Mixing LINQ to SQL with properties of objects in a generic list	var listOfIds = listOfObjects.Select(o => o.Id);\nvar query = \n    from a in DatabaseTable\n    where listOfIds.Contains(a.Id)\n    select a;	0
20304157	20304132	Is there a way that can be used to fill a listbox all at once with a list of object based on a specific property?	listBox1.Items.AddRange(latesProcessList.Select(p => p.ProcessName));	0
31410226	31410125	Dynamic property changing, C#	var eai = EventArgs.InterfaceInsideEventArg[index];\nvar eaz = EventArgs.InterfaceInsideEventArg[z];\n\neai.PropertyInsideInterface = eaz.PropertyInsideInterface.Replace("DeeperSkyBlue", "0066CC");\neai.{prop2} = eaz.{prop2}.Replace("DeeperSkyBlue", "0066CC");\n//etc.	0
23521970	23521755	How to get the binding value in code behind for phone call Task?	private void phonenumber_Tap(object sender, System.Windows.Input.GestureEventArgs e)\n    {\n        PhoneCallTask call = new PhoneCallTask();\n        call.PhoneNumber = ((TextBlock)sender).Text;\n        call.Show();\n     }	0
20052636	20052284	Binding a listbox to an observable collection - running out of ideas	public partial class MainWindow : Window\n{\n    private ObservableCollection<TestItem> testItems = new ObservableCollection<TestItem>();\n    public ObservableCollection<TestItem> TestItems { get { return  testItems ; }\n\n    public MainWindow()\n    {\n        InitializeComponent();   \n        this.DataContext = this;    \n        TestItem test = new TestItem("name", "type");    \n        this.testItems.Add(test);\n    }\n}	0
10223376	10223246	Use Linq to statistics data with average	var query = from _stats in _statsList \n    group _stats by new {\n               Latency = _stats.latency, \n               CpuUsagePercent = _stats.cpuUsagePercent, \n               MemoryUsagePercent = _stats.memoryUsagePercent, \n               DiskUsage = _stats.diskUsage, \n               DiskRead = _stats.diskRead, \n               DiskWrite = _stats.diskWrite\n\n    } into myGroup\n    select new {\n        AverageVal = myGroup.Average(x => x.Value),\n        CpuUsagePercent = myGroup.Key.CpuUsagePercent,\n        ... // the rest of your projection\n};	0
10975034	10974992	How to set a dropdownlist item as selected in ASP.NET?	dropdownlist.ClearSelection(); //making sure the previous selection has been cleared\ndropdownlist.Items.FindByValue(value).Selected = true;	0
4960612	4659119	Can i create a XmlNamespaceManager object from the xml file i am about to read?	NamespaceManager.AddNamespace("my", formXml.DocumentElement.NamespaceURI	0
17002586	17002522	Unable to convert MySQL date/time value to System.DateTime in VS2010	"Convert Zero Datetime=True"\n"Allow Zero Datetime=True"	0
30836065	30834732	Move windows form from a picturebox in C#	private bool draging = false;
\n        private Point pointClicked;
\n        private void pictureBox1_MouseMove(object sender, MouseEventArgs e)
\n        {
\n            if (draging)
\n            {
\n                Point pointMoveTo;
\n                pointMoveTo = this.PointToScreen(new Point(e.X, e.Y));
\n                pointMoveTo.Offset(-pointClicked.X, -pointClicked.Y);
\n                this.Location = pointMoveTo;
\n            }
\n        }
\n
\n        private void pictureBox1_MouseDown(object sender, MouseEventArgs e)
\n        {
\n            if (e.Button == MouseButtons.Left)
\n            {
\n                draging = true;
\n                pointClicked = new Point(e.X, e.Y);
\n            }
\n            else
\n            {
\n                draging = false;
\n            }
\n        }
\n
\n        private void pictureBox1_MouseUp(object sender, MouseEventArgs e)
\n        {
\n            draging = false;
\n        }	0
15224966	14802634	Stitching together an array of tiles	RenderTarget2D target = new RenderTarger2D(...); \n//I cant remeber the arguments off the top of my head.\n//I think its GraphicsDevice, Width, Height, GenerateMipmap, SurfaceFormat, Depthformat\n\nGraphicsDevice.SetRenderTarget(target);\nGraphicsDevice.Clear(Color.Black); //any colour will do\nusing(SpriteBatch b = new SpriteBatch(GraphicsDevice))\n{\n   b.Begin();\n\n   //Loop through all texture and draw them, so ...\n   for(int y = 0; y < 10; i++)\n     for(int y = 0; y < 10; i++)\n       batch.Draw(Texture, new Rectangle(xPos, yPos, width, height), Color.White));\n\n   b.End();\n}\n\nGraphicsDevice.SetRenderTarget(null);\n\n//Then to access your new Texture, just do \nTexture newTexture = target; //Target inherits from Texture2D so no casting needed	0
17802007	17784909	Create custom ComboBox with rounded corners in Windows Forms	public CustomComboBox()\n{\n    InitializeComponent();\n    SetStyle(ControlStyles.UserPaint, true);\n}	0
4469987	4469870	Dynamic Name to the Control Template in WPF?	private static void OnMyNamePropertyChanged(DependencyObject d,\n    DependencyPropertyChangedEventArgs e)\n{\n    // d is the object which the attached property has been set on\n}	0
2804305	2804256	Is it safe to access asp.net session variables through static properties of a static object?	public static class SessionHelper\n{\n\n    private static HttpSession sess = HttpContext.Current.Session;\n    public static int Age\n    {\n        get\n        {\n            return (int)sess["Age"];\n        }\n\n        set\n        {\n            sess["Age"] = value;\n        }\n    }\n}	0
891499	891345	Get a screenshot of a specific application	public void CaptureApplication(string procName)\n{\n    var proc = Process.GetProcessesByName(procName)[0];\n    var rect = new User32.Rect();\n    User32.GetWindowRect(proc.MainWindowHandle, ref rect);\n\n    int width = rect.right - rect.left;\n    int height = rect.bottom - rect.top;\n\n    var bmp = new Bitmap(width, height, PixelFormat.Format32bppArgb);\n    Graphics graphics = Graphics.FromImage(bmp);\n    graphics.CopyFromScreen(rect.left, rect.top, 0, 0, new Size(width, height), CopyPixelOperation.SourceCopy);\n\n    bmp.Save("c:\\tmp\\test.png", ImageFormat.Png);\n}\n\nprivate class User32\n{\n    [StructLayout(LayoutKind.Sequential)]\n    public struct Rect\n    {\n    public int left;\n    public int top;\n    public int right;\n    public int bottom;\n    }\n\n    [DllImport("user32.dll")]\n    public static extern IntPtr GetWindowRect(IntPtr hWnd, ref Rect rect);\n}	0
2895563	2895395	ListViewItem in WPF ListView	ListViewItem selectedListView = \n    (ListViewItem)listView1.ItemContainerGenerator.GetContainerForItem(\n        listView1.Items[index]);	0
31636261	31635469	How to convert string xml to json in c# and send over SOAP in C#	// To convert an XML node contained in string xml into a JSON string   \n    XmlDocument doc = new XmlDocument();\n    doc.LoadXml(xml);\n    string jsonText = JsonConvert.SerializeXmlNode(doc);\n\n    // To convert JSON text contained in string json into an XML node\n    XmlDocument doc = JsonConvert.DeserializeXmlNode(json);	0
24880593	24880505	How to get field as result of LINQ	var results = Table.Where(row => row.result != null)\n                   .Select(row => row.result)\n                   .ToArray();	0
354198	354068	How do I set a default role for a new user using Windows Authentication with the SqlRoleProvider?	protected void WindowsAuthentication_OnAuthenticate(object sender, WindowsAuthenticationEventArgs e)\n{\n    if (!Roles.IsUserInRole(e.Identity.Name, "Users"))\n    {\n        Roles.AddUsersToRole(new string[] { e.Identity.Name }, "Users");\n    }\n}	0
7671680	7671141	How i can get windows logon domain name from AD domain name	string username = "<username>";\n\nDirectoryEntry de = new DirectoryEntry(\n    "LDAP://" + ConfigurationManager.AppSettings["ADDomain"],\n    ConfigurationManager.AppSettings["ADUsername"],\n    ConfigurationManager.AppSettings["ADPassword"]);\n\nDirectorySearcher ds = new DirectorySearcher(de);\nds.Filter = string.Format("samaccountname={0}",\n    (username.Split('\\').Length > 1) ? username.Split('\\')[1] : username);\n\nSearchResult result = ds.FindOne();\nif (result == null)\n    throw new ArgumentException(\n        string.Format("Username '{0}' does not exist in the active directory", username), "username");	0
12292223	11809566	Click button to continue with next method	do\n{Application.Doevents()}\nwhile (step == false)	0
33459055	33458887	Create a tree from a list in C#, with grouping	var nodes = list\n    .GroupBy(c1 => c1.Cat1.Name)\n    .Select(c1 => new Node\n    {\n        Name = c1.Key,\n        Weight = c1.Sum(x => x.Weight),\n        Children = c1\n            .GroupBy(c2 => c2.Cat2.Name)\n            .Select(c2 => new Node\n            {\n                Name = c2.Key,\n                Weight = c2.Sum(x => x.Weight),\n                Children = c2.Select(c3 => new Node\n                {\n                    Name = c3.Cat3.Name,\n                    Weight = c3.Weight,\n                    Children = new List<Node>()\n                }).ToList()\n            }).ToList()\n\n    }).ToList();	0
1313679	1313673	Execute PowerShell as an administrator from C#	using ( new Impersonator( "myUsername", "myDomainname", "myPassword" ) )\n{\n    using (RunspaceInvoke invoker = new RunspaceInvoke())\n    {\n        invoker.Invoke("Set-ExecutionPolicy Unrestricted");\n    }\n}	0
31978369	31978212	C# Loading Data from an Associated File Type	"My Program.exe" "%1"	0
10323206	10322388	Using a enum with flag in an Entity Framework query	public static Dictionary<int, int> map = new Dictionary<int, int>() { { 0, 64 }, { 1, 1 }, { 2, 2 }, { 3, 4 }, { 4, 8 }, { 5, 16 }, { 6, 32 } };\n\n//actually,this gets from a user interface,but we shoul be focus database layer\nWeekDays[] dw = new WeekDays[] {WeekDays.Saturday,WeekDays.Tuesday,WeekDays.Wednesday };\n\nint[] systemDayOfWeekList = new int[daysOfWeek.Length];\n\nfor (int i = 0; i < daysOfWeek.Length; i++)\n{\n  systemDayOfWeekList[i] = map.FirstOrDefault(e => e.Value == (int)daysOfWeek[i]).Key;\n}\n\nquery = query.Where(f => dayOfWeekList.Contains(((int)SqlFunctions.DatePart("dw", f.FromDateTime))));	0
9671996	9670113	PropertyGrid: Trouble with ExpandableObjectConverter	Class2 class2 = new Class2();	0
25814905	25814603	How to set the visibility of a ProgessBar in WPF?	private void MethodThatWillCallComObject()\n        {\n            System.Threading.Tasks.Task.Factory.StartNew(() =>\n            {\n                //this will call in background thread\n                return this.MethodThatTakesTimeToReturn();\n            }).ContinueWith(t =>\n            {\n                //t.Result is the return value and MessageBox will show in ui thread\n                MessageBox.Show(t.Result);\n            }, System.Threading.Tasks.TaskScheduler.FromCurrentSynchronizationContext());\n        }\n\n        private string MethodThatTakesTimeToReturn()\n        {\n            System.Threading.Thread.Sleep(5000);\n            return "end of 5 seconds";\n        }	0
8609173	8609117	How is the critical section associated with every Object initialized?	Monitor.Enter	0
2997586	2988352	How to attach different EventHandlers to combos of a single DataGridView	public void dvgCombo_SelectedIndexedChanged()\n{\n    if (<condition1>)\n        ExecuteConditionOneLogic();\n\n    if (<condition2>)\n        ExecuteConditionTwoLogic();\n\n}	0
26500366	26500205	C# - Inserting DataSet that contains relational DataTables into Sql Server	string connectionString = "your_connection_string";  \nSqlConnection con = new SqlConnection(connectionString);  \n\ntry  \n{  \n    con.Open();  \n    string query = "insert statement";  \n\n    using (SqlCommand cmd = new SqlCommand(query, con))  \n    {  \n        cmd.Parameters.AddWithValue("@some_parameter", "value_of_some_parameter");  \n        cmd.ExecuteNonQuery();  \n    }   \n}  \ncatch (Exception)  \n{  \nthrow;  \n}	0
22870062	22815693	How do you set Entity Framework to cascade on delete with optional foreign key?	void Delete(bool recursive = false)\n{\n    if(recursive)\n        RecursiveDelete();\n\n    if(this.Parent != null)\n        this.Parent.Children.Remove(this);\n\n    using(var db = new MyContext())\n    {\n        db.SaveChanges();\n    }\n}\nvoid RecursiveDelete()\n{\n    foreach(var child in Children.ToArray())\n    {\n        child.RecursiveDelete();\n        Children.Remove(child);\n    }\n\n    using(var db = new MyContext())\n    {\n        db.Nodes.Attach(this);\n        db.Entry(this).State = EntityState.Deleted();\n    }\n}	0
131980	131944	How do I read a time value and then insert it into a TimeSpan variable	string input = "08:00";\nDateTime time;\nif (!DateTime.TryParse(input, out time))\n{\n    // invalid input\n    return;\n}\n\nTimeSpan timeSpan = new TimeSpan(time.Hour, time.Minute, time.Second);	0
31526648	31526588	Issue with Xml and dataset	DataSet.WriteXml	0
29005438	29005293	How to in general convert classes to xml nodes?	public class Rootobject\n     {\n        public string xmlns { get; set; }\n        public string text { get; set; }\n     }\n\n\n\n    public static void Main(string[] args) \n    { \n      Rootobject details = new Rootobject();\n      details.xmlns = "myNamespace";\n      details.text = "Value";\n\n      Serialize(details);\n   }   \n\n   static public void Serialize(Rootobject details)\n   { \n     XmlSerializer serializer = new XmlSerializer(typeof(Rootobject)); \n     using (TextWriter writer = new StreamWriter(@"C:\Xml.xml"))\n     {\n       serializer.Serialize(writer, details); \n     } \n   }	0
3689892	3689655	Advanced fading of one picture to another	void backgroundWorker_DoWork(object sender, DoWorkEventArgs e) {\n  long ticks1 = 0;\n  long ticks2 = 0;\n  double interval = (double)Stopwatch.Frequency / 60;\n  while (true) {\n    ticks2 = Stopwatch.GetTimestamp();\n    if (ticks2 >= ticks1 + interval) {\n      ticks1 = Stopwatch.GetTimestamp();\n\n      if(_fadeIn){\n        _fadeAlpha += 0.1f;\n        if(_fadeAlpha > 1f){\n          _fadeAlpha = 1f;\n          break;\n        }\n      }else{\n        _fadeAlpha -= 0.1f;\n        if(_fadeAlpha < 0f){\n          _fadeAlpha = 0f;\n          break;\n        }\n      }\n      backgroundWorker.ReportProgress(0);\n    }\n    Thread.Sleep(1);\n  }\n  backgroundWorker.ReportProgress(0);\n}	0
7160559	7160459	listbox; number of selected items	listbox1.GetSelectedIndices().Count();	0
27496068	27495943	AutoMapper from a list to collection grouped by date	Mapper.CreateMap<ModelChild, DayViewModel>()\n    .ConstructUsing(context =>\n    {\n        var key = ((ModelChild) context.SourceValue).Started;\n        var daysCollection = (SortedSet<DayViewModel>) context.Parent.DestinationValue;\n\n        var dayViewModel = daysCollection.FirstOrDefault(d => d.Date == key);\n\n        if (dayViewModel == null)\n        {\n            dayViewModel = new DayViewModel\n            {\n                Date = key\n            };\n\n            daysCollection.Add(dayViewModel);\n        }\n\n        dayViewModel.Children.Add(Mapper.Map<ChildViewModel>(context.SourceValue));\n        return dayViewModel;\n    })\n    .ForAllMembers(d => d.Ignore());	0
32158016	32157883	How to resolve custom type while passing object as argument	public class ProductService\n{\n    public void Create<T>(T obj)\n    {\n        if (typeof(Supplier) == typeof(T))\n            Supplier(obj); //Call Supplier Method;\n        else if (typeof(Product) == typeof(Product))\n            Product(); //Call Product Method;\n        else\n            throw new ArgumentOutOfRangeException("Unrecognized type", "type");\n    }\n\n    private void Supplier<T>(T s)\n    {\n        //statements\n        Console.WriteLine("Supplier");\n    }\n    private void Product()\n    {\n        //statements\n        Console.WriteLine("Product");\n    }\n}	0
12369661	12369331	Replace New Attribute's Value	var xd = XDocument.Parse(@"<Identification LastName=""Bornery"" Name=""John"" Age=""23""/>");\nxd.Element("Identification").Attribute("Age").Value = "40";\nstring result = xd.ToString();	0
10788469	10788366	How to read XML data dynamically in C#/.net?	string id = "1"\n\n\nXDocument doc = XDocument.Load("data.xml");\nvar accounts = from elements in doc.Elements("HOSTS").Elements("Host")\n                where elements.Attribute("id").Value = id\n                    select elements.FirstOrDefault();	0
14881864	14880814	How to print the nodes from XMLNodeList	XmlDocument doc = new XmlDocument(); \ndoc.Load("C:\\Users\\hsyed\\Documents\\XMLParser\\Example.xml");\n\nXmlNodeList nodes = doc.SelectNodes("//root/Identities/Identity/Refrences/Reference/Value/text()");\n\nforeach (XmlNode xn in nodes)\n{\n    Console.WriteLine(xn.Value.ToString());\n}	0
13519282	13519169	Reading from CSV file and store to an array	using (StreamReader r = new StreamReader(guid.ToString()))\n{\n    string line;\n    int linesCount;\n    ArrayList result = new ArrayList();\n    while ((line = r.ReadLine()) != null && linesCount++ <= 200)\n    {\n         result.AddRange(line.Split(','));\n    }\n}	0
15114362	14663017	Do I need a deep copy?	// Creates a deep copy of an Object\npublic static T DeepClone<T>(T obj)\n{\n    using (var ms = new MemoryStream())\n    {\n        var formatter = new BinaryFormatter();\n        formatter.Serialize(ms, obj);\n        ms.Position = 0;\n\n        return (T)formatter.Deserialize(ms);\n    }\n}	0
6026082	6025674	how to set display member to a concatenated expression? datasource is linq query	var query =\n                from a in db.LUT_Employees\n                where a.position == "Supervisor" && a.department == "Production"\n                select new { a, Names = a.lastName + ", " + a.firstName };\n\n            cboProductionSupervisor.DataSource = query;\n            cboProductionSupervisor.DisplayMember = "Names";	0
14071603	14059606	Capturing a Click on a NativeWindow	protected override void WndProc(ref System.Windows.Forms.Message m)\n    {\n        const int TTM_RELAYEVENT = 0x407;\n        if (m.Msg == TTM_RELAYEVENT)\n        {\n            Message relayed = (Message)Marshal.PtrToStructure(m.LParam, typeof(Message));\n            if (related.Msg == WM_LBUTTONDOWN)\n            {\n                // Do something\n            }\n        }\n\n        base.WndProc(ref m);\n    }	0
6167441	6167400	C# MySql Storing multiple database rows in C#	string strConnection = ConfigurationSettings.AppSettings["ConnectionString"];\n     MySqlConnection connection = new MySqlConnection(strConnection);\n\n     List<string> array = new List<string>();\n\n        using (MySqlCommand cmd = new MySqlCommand("SELECT idprojects FROM `test`.`projects` WHERE application_layers = " + applicationTiers, connection))\n        {\n            try\n            {\n                using (MySqlDataReader Reader = cmd.ExecuteReader())\n                {\n                    while (Reader.Read())\n                    {\n                        array.Add(Reader["idprojects"].ToString());\n                    }\n                }\n            }\n\n            catch (Exception ex)\n            {\n                throw;\n            }\n        }\n\n        string[] ret= array.ToArray();	0
27145662	27145507	How to replace characters in a string in c#	String dna="ACTG";\nString dnaComplement = "";\n\nforeach(char c in dna)\n{\n  if (c == 'A') dnaComplement += 'T';\n  else if (c == 'C') dnaComplement += 'G';\n // and so long\n}	0
30942056	30941971	Multiple keys with WPF KeyDown event	else if.....	0
13103190	13103158	Custom Attribute to determine if method can process	[Serializable]\npublic class LogAttribute : OnMethodBoundaryAspect\n{\n    public override void OnEntry(MethodExecutionArgs args)\n    {\n        if (!application.running)\n            throw new Exception(String.Format("Method {0} is not allowed to call when application is not running.", args.Method.Name));\n    }\n}	0
22517577	22513495	How to parse XML using c# and XDocument into an object when multiple elements have the same name?	private readonly XNamespace a = "http://www.w3.org/2005/Atom";\nprivate readonly XNamespace d = "http://schemas.microsoft.com/ado/2007/08/dataservices";\nprivate readonly XNamespace m = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";\n\nList<KLList> lists = doc.Descendants(a + "entry").Where(element => element.Attribute(m + "etag") != null).Select(\n    list => new KLList()\n    {\n        Id = list.Descendants(d + "Id").FirstOrDefault().Value,\n        Title = list.Descendants(d + "Title").FirstOrDefault().Value,\n        ListItemEntityTypeFullName = list.Descendants(d + "ListItemEntityTypeFullName").FirstOrDefault().Value,\n        BaseType = (BaseType)Convert.ToInt32(list.Descendants(d + "BaseType").FirstOrDefault().Value),\n        ListTemplateType = (ListTemplateType)Convert.ToInt32(list.Descendants(d + "BaseTemplate").FirstOrDefault().Value),\n        RelativeUrl = list.Descendants(d + "ServerRelativeUrl").FirstOrDefault().Value\n    }).ToList();	0
2575664	2575644	Socket Communication C#- IP Address	IPAddress.Any	0
26362733	26362343	How to get Drag and Drop to work on Windows 7	e.Effect	0
29709295	29707530	Execute Expression Stored in a String	private CalculationEngine engine = new CalculationEngine();\n\n private void ExecuteButton_Click(object sender, RoutedEventArgs e)\n {\n    double result = engine.Calculate(ExpressionTextBox.Text);\n    ExpressionTextBox.Text = result.ToString();  // displays the result\n }	0
9665848	9637561	MS Chart: How can you change the color of each label on the Axis of a Bar Chart?	this._chart.ChartAreas[0].AxisX.CustomLabels.Add(new CustomLabel(position - 1, position + 1, point.AxisLabel, 0, LabelMarkStyle.None));\n\nthis._chart.ChartAreas[0].AxisX.CustomLabels[position - 1].ForeColor = GetColor(point.AxisLabel);	0
1185603	1185173	Bind to element's position relative to a parent in WPF	DependencyPropertyDescriptor dpd = DependencyPropertyDescriptor.FromProperty(Canvas.TopProperty, typeof(Canvas));\n\ndpd.AddValueChanged(canvas1, new EventHandler(topChangedCallback));	0
13144702	12300024	Replacing Bookmark Range within Word document with formatted (HTML) text	public void ReplaceBookmarkTextWithHtml(Bookmark bookmark, string html)\n{\n    if (html != null) {\n        Clipboard.SetData(DataFormats.Html, ClipboardFormatter.Html(html));\n        bookmark.Range.PasteSpecial(DataType: WdPasteDataType.wdPasteHTML);\n    }\n}	0
5049571	5049562	How to calculate financial year start and end dates from financial year's month end value?	DateTime startDate = new DateTime(DateTime.Today.Year, 2, 1); // 1st Feb this year\nDateTime endDate = new DateTime(DateTime.Today.Year+1, 2, 1).AddDays(-1); // Last day in January next year	0
1113461	1113437	Drawing Colors in a picturebox?	private void pictureBox_Paint(object sender, PaintEventArgs e)\n{\nGraphics graphics = e.Graphics;\n\nBrush brush = new SolidBrush(Color.Red);\ngraphics.FillRectangle(brush, new Rectangle(10, 10, 100, 100));\n\nPen pen = new Pen(Color.Green);\ngraphics.DrawRectangle(pen, new Rectangle(5, 5, 100, 100));\n}	0
32382375	32381072	Is there any way to set Date only through ReadLine() to a DateTime type variable? How?	DateTime Dob;\nConsole.WriteLine("Enter date of Birth in format MM/DD/YYYY: ");\n//accepts date in MM/dd/yyyy format\nDob = DateTime.Parse(Console.ReadLine());	0
32338376	32338124	To Enable right click in disabled control	private void YourFormName_Load(object sender, EventArgs e)\n{\n     ContextMenu mnu = new ContextMenu();\n     MenuItem mnuCopy = new MenuItem("Copy");\n     mnuCopy.Click += (sen, ev) =>\n     { \n         System.Windows.Forms.Clipboard.SetText(YourTextBoxName.Text);\n     };\n     mnu.MenuItems.AddRange(new MenuItem[] { mnuCopy });\n     YourTextBoxName.ContextMenu = mnu;\n}\n\nprivate void YourFormName_MouseUp(object sender, MouseEventArgs e)\n{\n    Control ctl = this.GetChildAtPoint(e.Location);\n    if (ctl != null && !ctl.Enabled && ctl.ContextMenu != null)\n    ctl.ContextMenu.Show(this, e.Location);\n}	0
3006788	3005469	Determining whether a class implements a generic list in a T4 template	node.BaseType.IsGeneric && node.BaseType.Template == FrameworkAssemblies.Mscorlib.Types.SingleOrDefault(t => t.FullName == "System.Collections.Generic.List`1")	0
32922737	32922658	Efficient way to export data from datatable object to Excel	XLWorkbook wb = new XLWorkbook();\nDataTable dt = GetDataTableOrWhatever();\nwb.Worksheets.Add(dt,"WorksheetName");	0
2841041	2840915	Help making Fluent NHibernate create an oracle sequence for each table	public class OraclePrimaryKeySequenceConvention : IIdConvention\n{\n    public void Apply(IIdentityInstance instance)\n    {\n        instance.GeneratedBy.Sequence(string.Format("Sequence_{0}",\n                                                    instance.EntityType.Name));\n    }\n}	0
34502600	34502290	How to get the value from my picker? Xamarin forms	picker.SelectedIndexChanged += (sender, args) =>\n            {\n                if (picker.SelectedIndex == -1)\n                {\n                    boxView.Color = Color.Default;\n                }\n                else\n                {\n                    string colorName = picker.Items[picker.SelectedIndex];\n                    boxView.Color = nameToColor[colorName];\n                }\n            };	0
10007221	10007106	The best way to wait for a UI control?	{ \n    // before code snippet.. \n    await messageDisplayer1.ShowMessage("test", true); \n    // after code snippet.. \n}	0
34481821	34481620	How to execute a method everyday morning in c# .net	while(true)\n{\n    if(DateTime.Now.Hour == 6 && DateTime.Now.Minute == 0)\n       Processmethod();\n    else\n       Thread.Sleep(1000)\n}	0
19184853	19184754	ASP.NET - Validating Form Before Standard Validation	onclientclick="test()"	0
34487376	34487111	Sqlite WHERE LIKE statement c#	public IEnumerable<Table1> Method1()\n    {\n        string StrSql = "Select * From [Table1] Where [Name] in (";\n        List<string> par = fav.Split(',').ToList();\n        foreach (string _par in par)\n        {\n            StrSql += "'" + _par + "'";\n            if (_par != par.Last())\n            {\n                StrSql += ',';\n            }\n            else\n            {\n                StrSql += ")";\n            }\n        }\n        return conn.Query<Table1>(StrSql);\n    }	0
7644795	7644610	how add a string to focused texbox in winform c#	myFormInstance.ActiveControl	0
3079430	3079388	How can I convert Cyrillic string into English in c#	var map = new Dictionary<char, string>\n{\n    { '?', "P" },\n    { '?', "e" },\n    { '?', "t" },\n    { '?', "r" },\n    ...\n}\n\nvar result = string.Concat("?????????".Select(c => map[c]));	0
15227390	15226387	Implementing Interfaces with Collections and Generics	Partial EntityClassA : InterfaceA\n{\n    IEnumerable<InterfaceB> CollectionEntityClassBs\n    {\n        get{ return (some cast or somthin)EntityClassBs;  }\n    }\n}\n\nInterfaceA\n{\n   IEnumerable<InterfaceB> CollectionEntityClassBs;\n}	0
9995812	9995661	Regular expression needed to remove custom markup tags	var r = new Regex("<A[GHI]>!(.+?)!");\nvar actual = r.Replace(xml, "$1");	0
13377363	13377211	Basic Tab Control	private void calculateButton_Click(object sender, EventArgs e)\n        {\n            if (tabControl.SelectedTab == tab1)\n            {\n                 MessageBox.Show("whatever");\n            }\n            else\n            {\n                 MessageBox.Show("doesnt matter");\n            }\n        }	0
34230836	34230728	How to find out the XAML file that produces a XamlParseException	public partial class Window1 : System.Windows.Window\n{\npublic Window1()\n{\n  try\n\n  {\n    InitializeComponent();\n  }\n  catch ( Exception ex )\n  {\n  // Log error (including InnerExceptions!)\n  // Handle exception\n   MessageDialog dialog = new MessageDialog(ex.InnerException);\n   dialog.ShowAsync();\n\n  }\n }\n}	0
33985211	33984383	Nothing retrived from webservice object response in android	android.os.NetworkOnMainThreadException	0
29266667	29240430	Invalid Parameters Execption using sequence	Bitmap imga = ...;\npictureBox0.Image = imga;\npictureBox1.Image = imga;\npictureBox2.Image = imga;\npictureBox3.Image = imga;\nimga = ...;\npictureBox4.Image = imga;\npictureBox5.Image = imga;\npictureBox6.Image = imga;\npictureBox7.Image = imga;\n...	0
14514256	14513700	Invalid cast when getting custom IPrincipal from HttpContext	var custom = Context.Current as MyCustomPrinciple;\nif(custom == null)\n{\n// Your construct code here.\n}	0
34268111	34263134	Order by array values in Linq to Entity Framework Query	var countByOtherId = db.EntityToOrder\n    .GroupBy(e => e.OtherId)\n    .Select(g => new { ID = g.Key, Count = g.Count() })\n    .ToDictionary(e => e.ID, e => e.Count);\n\nvar other = new Dictionary<long, string>();\nint skipCount = startIndex, useCount = 0;\nforeach (var e in db.OtherEntity.OrderBy(e => e.Name))\n{\n    int count;\n    if (!countByOtherId.TryGetValue(e.ID, out count)) continue;\n    if (skipCount > 0 && other.Count == 0)\n    {\n        if (skipCount >= count) { skipCount -= count; continue; }\n        count -= skipCount;\n    }\n    other.Add(e.ID, e.Name);\n    if ((useCount += count) >= pageSize) break;\n}\n\n\nvar entities = db.EntityToOrder\n    .Where(e => other.Keys.Contains(e.OtherId))\n    .AsEnumerable()\n    .Select(e => new EntityToOrder { ID = e.ID, Name = e.Name, \n        OtherId = e.OtherId, OtherName = other[e.OtherId] })\n    .OrderBy(e => e.OtherName).ThenBy(e => e.Name)\n    .Skip(skipCount).Take(pageSize)\n    .ToList();	0
22996438	22995978	Finding unknown repeating patterns in a string consisting numbers	string FindPattern(string text)\n{\n    if (text == null)\n    {\n        return null;\n    }\n\n    return Enumerable\n        .Range(1, text.Length / 2)\n        .Where(n => text.Length % n == 0)\n        .Select(n => text.Substring(0, n))\n        .Where(pattern => Enumerable\n            .Range(0, text.Length / pattern.Length)\n            .SelectMany(i => pattern)\n            .SequenceEqual(text))\n        .FirstOrDefault();\n}	0
12334722	12334639	C# Dynamic method invoke for Task as an Action	MethodInfo methodInfo = typeof(MyClass).GetMethod(task.Command);\nif (methodInfo != null)\n  Task.Factory.StartNew(() => methodInfo.Invoke(this, new []{ task }));	0
14084172	14084086	How to generate time and date in C# and format it for mysql?	DateTime time = DateTime.Now;              \n    string format = "yyyy-MM-dd HH:mm:ss";   \n    var mytime = time.ToString(format);	0
19800675	19795980	How to retrieve the names of all the named instances in StructureMap	var policyNames =  Container.Model.AllInstances.Where(x => x.PluginType == typeof(IPolicy)).Select(x => x.Name);	0
17437617	17437502	How to work with with PathGeometry Class	var streamGeometry = StreamGeometry.Parse("F1 M 35,19L 41,19L 41,35L 57,35L 57,41L 41,41L 41,57L 35,57L 35,41L 19,41L 19,35L 35,35L 35,19 Z ");\n                    sortButton.IconData = streamGeometry;	0
28228544	28227999	How to scale image from center? Windows 8.1 C#	img.RenderTransformOrigin = new Point(0.5, 0.5);	0
24892641	24892598	Pick out value from Json	public static void GoogleGeoCode(string address)\n{\n    string url = "http://maps.googleapis.com/maps/api/geocode/json?sensor=true&address=";\n    dynamic googleResults = new Uri(url + address).GetDynamicJsonObject();\n\n    foreach (var result in googleResults.results)\n    {\n        Console.WriteLine("[" + result.geometry.location.lat + "," + \n                            result.geometry.location.lng + "] " + \n                            result.formatted_address);\n    }\n}	0
3812573	3812548	showing newline in label	lblSaleData.Text = "&lt;Sales&gt;" + "<br/>" + \n"&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&lt;eml&gt;" + eml + \n"&lt;/eml&gt;" + "<br/>"+ "&lt;/Sales&gt;";	0
31086694	31086571	Looping through single nodes in HTMLAgilityPack in C#	itemUrl = obj.SelectSingleNode(".//a").Attributes["href"].Value, itemId = obj.SelectSingleNode(".//article").Attributes["data-id"].Value	0
13996214	13995035	How does one require a password to be changed when setting an Active Directory password programmatically?	using (var context = new PrincipalContext( ContextType.Domain ))\n{\n  using (var user = UserPrincipal.FindByIdentity( context, IdentityType.SamAccountName, userName ))\n  {\n      user.SetPassword( "newpassword" );\n      user.ExpirePasswordNow(();\n  }\n}	0
22617287	22616476	How to read form-url encoded response	var testData = "{\r\n\t\"status\":\"Success\"\r\n}";\ndynamic testObject = JsonConvert.DeserializeObject(testData);\nConsole.WriteLine(testObject.status); //Success\nConsole.ReadKey();	0
10643607	10643537	Fastest way to read a file	BULK INSERT	0
13756310	13736344	Using GE Plugin, how do I programmatically put placemarks in folders?	KmlTreeViewNode node = kmlTreeView1.GetNodeById("Sites"); // get the empty node you added to the tree\nnode.ApiObject.getFeatures().appendChild(placemark); // get the KmlFolder and add a placemark\nge1.getFeatures().appendChild(node.ApiObject); // add the KmlFolder and features to the plugin\nkmlTreeView1.Nodes.RemoveByKey("sites"); // remove the empty node from the tree...\nkmlTreeView1.ParseKmlObject(node.ApiObject); // add the KmlFolder that contains your placemark	0
12176885	11466393	Is it possible to disable one listItem from radioButton list in asp.net 	protected void Page_Load(object sender, EventArgs e)\n {\n   string planType=Request.QueryString["type"];\n   if (planType == "False")\n    {\n      rdodomiantype.Items.Remove(rdodomiantype.Items.FindByValue("1"));\n    }\n }	0
16687393	16687162	How to exchange object between 2 .Net Application	[DataContract]\npublic class Message\n{\n    [DataMember]\n    public string Info {get; set;}\n\n    //Other Properties.\n}	0
1605832	1605809	RegEx Replace and replacement string	return string.Format("<dfn title=\"{0}\">{1}</dfn>",\n                     this.FindDefinition(m.Value),\n                     m.Value);	0
19712098	19710812	How do I get the file contents of a MultipartMemoryStreamProvider as a byte array?	i.ReadAsByteArrayAsync()	0
27858152	27856995	How to check data when using binding in WPF	private string name;\n\npublic string Name \n{\n    get\n    {\n        return name;\n    }\n\n    set\n    {           \n        CheckName(value); // Or whatever are you check functions\n\n        name = value;\n\n        PropertyChanged("Name");\n    }\n}	0
12733434	12733395	Copying properties from a model back to an object -- copy explicitly or iterate over property collection?	Mapper.CreateMap<Order, OrderDetailsModel>();\nOrderDetailsModel dto = Mapper.Map<Order, OrderDetailsModel >(order);	0
11222052	11222001	C#: Initialising member variables to be exposed via properties	public string ConnectionString { get; set; }\npublic string ProviderName { get; set; }\n\npublic EntityClusterRefreshServiceDatabaseWorker()\n{\n    // Code as before\n    ConnectionString = ...;\n    ProviderName = ...;\n}	0
30491732	30491630	Having constraints into constraints	public class UblConverter<TParser, TDto, TUbl> where TParser : UblParser<TDto, TUbl> \n                                               where TUbl : UblBaseDocumentType \n                                               where TDto : DtoB \n{\n    //...\n}	0
32168646	32168586	How to insert current date and time in sql server database using timestamp datatype?	create table user3(uname varchar(50) primary key,email varchar(50),doj datetime);	0
31377558	31374628	Fast way of finding most and least significant bit set in a 64-bit integer	public static UInt64 CountLeadingZeros(UInt64 input)\n{\n    if (input == 0) return 64;\n\n    UInt64 n = 1;\n\n    if ((input >> 32) == 0) { n = n + 32; input = input << 32; }\n    if ((input >> 48) == 0) { n = n + 16; input = input << 16; }\n    if ((input >> 56) == 0) { n = n + 8; input = input << 8; }\n    if ((input >> 60) == 0) { n = n + 4; input = input << 4; }\n    if ((input >> 62) == 0) { n = n + 2; input = input << 2; }\n    n = n - (input >> 63);\n\n    return n;\n}	0
7439410	7439313	Can we add datetime picker to datagridview's columns in winforms?	public class CalendarCell : DataGridViewTextBoxCell\n{\n\n...\n\npublic class CalendarEditingControl : DateTimePicker, IDataGridViewEditingControl\n{\n\n...	0
13628416	13628255	C# equivalent of C++ ostream::tellp for size limit on diskette	swOutput.BaseStream.Position	0
30366875	30051446	Need to convert code from c# to java	for (char ch : word.toCharArray()) {\n\n            if (ch >= 'B' && ch <= 'F' && soundexString.length() < 4) {\n\n                ... ...\n...\n            }\n        }	0
14257922	14257697	Passing multiple parameter via GET with params keyword to an MVC controller action	routes.MapRoute("Name", "param/{*params}", new { controller = ..., action = ... });\n\nActionResult MyAction(string params) {\n    foreach(string param in params.Split("/")) {\n        ...\n    }\n}	0
4723011	4722876	How to get PropertyDescriptor for current property?	public string Test\n        {\n            get\n            {\n                //Get properties for this\n                System.ComponentModel.PropertyDescriptorCollection pdc = System.ComponentModel.TypeDescriptor.GetProperties( this );\n\n                //Get property descriptor for current property\n                System.ComponentModel.PropertyDescriptor pd = pdc[ System.Reflection.MethodBase.GetCurrentMethod().Name ];\n            }\n        }	0
17836729	17836689	Opening URL using an ImageButton	protected void Open_Click(object sender, System.Web.UI.ImageClickEventArgs e)\n{\n    try\n    {\n        Response.Redirect("http://www.website.com");\n    }\n    catch { }\n}	0
7999664	7998201	Finding a row in a datatable that is the closest to my parameters	var closest = data.Select().\n    OrderBy(dr => Math.Abs((int)dr["TRK_Distance"] - 1600)).\n    FirstOrDefault();	0
4516697	4516637	using windows username password in C#	PrincipalContext pc = new PrincipalContext(ContextType.Domain);\nbool isCredentialValid = pc.ValidateCredentials(username, password);	0
12747265	12747194	Bring window to the front	this.WindowState = FormWindowState.Maximized; // To maximize\n this.WindowState = FormWindowState.Normal; // To restore	0
11567427	11567382	Convert Dictionary<string, object> to a collection of objects with key	var myCollection = from de in myDictionary \n                   select new\n                   {\n                       de.Value.property1,\n                       de.Value.property2,\n                       de.Key\n                   }.ToList();  // or .ToArray()	0
25434568	25434409	Best way to create multiple classes in a database	public class Estimate {\n   public string Name { get; set; }\n   public List<Option> Options { get; set; }\n\n   public Estimate() {\n      Options = new List<Option>();\n   }\n}\n\npublic class Option {\n   public int Id { get; set; }\n   public string Description { get; set; }\n   public Estimate Estimate { get; set; }\n}	0
4288588	4288116	Winforms C# app using sockets works under winXp, but throws error under Windows 7	if(Socket.OSSupportsIPv6 && _hostIpAddress.AddressFamily == AddressFamily.InterNetworkV6) \n{\n   // newer OS\n   _socketConnection = new Socket(\n       AddressFamily.InterNetworkV6, \n       SocketType.Stream, \n       ProtocolType.Tcp);\n   _socketConnection.SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.IPv6Only, 0);\n} else { \n   // older OS\n   _socketConnection = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);\n}	0
899829	372693	Convert string to Brushes/Brush color name in C#	// best, using Color's static method\nColor red1 = Color.FromName("Red");\n\n// using a ColorConverter\nTypeConverter tc1 = TypeDescriptor.GetConverter(typeof(Color)); // ..or..\nTypeConverter tc2 = new ColorConverter();\nColor red2 = (Color)tc.ConvertFromString("Red");\n\n// using Reflection on Color or Brush\nColor red3 = (Color)typeof(Color).GetProperty("Red").GetValue(null, null);\n\n// in WPF you can use a BrushConverter\nSolidColorBrush redBrush = (SolidColorBrush)new BrushConverter().ConvertFromString("Red");	0
9488864	9488791	How to append a control character to a string in c#?	byte[] unicodeBytes = Encoding.Unicode.GetBytes(ackMessage);\n    var asciiBytes = new List<byte>(ackMessage.Length + 3);\n    asciiBytes.Add(0x0b);\n    asciiBytes.AddRange(Encoding.Convert(Encoding.Unicode, Encoding.ASCII, unicodeBytes));\n    asciiBytes.AddRange(new byte[] { 0x1c, 0x0d });	0
8119730	7821639	How to create Internet Explorer sidebar extension in C#?	"C:\Program Files (x86)\Microsoft SDKs\Windows\v7.0A\Bin\NETFX 4.0 Tools\gacutil.exe" /f /i "$(TargetDir)$(TargetFileName)"\n\n"C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe" /unregister "$(TargetDir)$(TargetFileName)"\n\n"C:\Windows\Microsoft.NET\Framework\v4.0.30319\RegAsm.exe" "$(TargetDir)$(TargetFileName)"	0
14100362	14100148	MEF plugin can't find referenced library	public static class AssemblyResolverFix\n{\n  //Looks up the assembly in the set of currently loaded assemblies,\n  //and returns it if the name matches. Else returns null.\n  public static Assembly HandleAssemblyResolve( object sender, ResolveEventArgs args )\n  {\n    foreach( var ass in AppDomain.CurrentDomain.GetAssemblies() )\n      if( ass.FullName == args.Name )\n        return ass;\n    return null;\n  }\n}\n\n//in main\nAppDomain.CurrentDomain.AssemblyResolve += AssemblyResolverFix.HandleAssemblyResolve;	0
8778769	8778656	how to set valuetype as positive int?	dgv.Columns[i].ValueType = typeof(uint);	0
26930377	26930262	C# Combine many IList<char> to make a new List	int[] numbers = { 1, 1, 3, 2, 2, 2 };\nint[] words = { 1, 1, 2, 3, 2, 2 };\n\nvar result = numbers.Zip(words, (first, second) => {if(first != second) {return first + " / " + second;} else return second.ToString(); });	0
24184912	24184789	Get maximum number of dots in a string-property of a class in a List<T>?	int maxDotNumber = kok.Max(k => k.Title.Count(c => c == '.'));	0
13342364	13342172	Updating XML attribute in subtree using LINQ to XML	var query =\n    from c in document.Root.Elements("Customer")\n    where c.Attribute("id").Value == customerID.ToString()\n    from a in c.Element("Accounts").Elements("Account")\n    where a.Attribute("id").Value == this.id.ToString()\n    select a;\n\nquery\n    .First()\n    .Attribute("money")\n    .SetValue(money.ToString());	0
15008321	15007812	Searching if an array of strings contain an array if char's	using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nclass Program\n{\n    static void Main(string[] args) {\n        var letters = args[0];\n\n        var wordList = new List<string> { "abcbca", "bca", "def" };\n\n        var results = from string word in wordList\n                      where IsValidAnswer(word, letters)\n                      orderby word.Length descending\n                      select word;\n\n        foreach (var result in results) {\n            Console.WriteLine(result);    \n        }\n    }\n\n    private static bool IsValidAnswer(string word, string letters) {\n        foreach (var letter in word) {\n            if (letters.IndexOf(letter) == -1) {\n                return false;\n            }\n\n            letters = letters.Remove(letters.IndexOf(letter), 1);\n        }\n\n        return true;\n    }\n}	0
22599907	22599824	Saving null DateTime on mvc3	DateTime enteredDate;\nDateTime.TryParse(workerDateAcquired, out enteredDate);\n\nskill.DateAcquired = enteredDate.Equals(DateTime.MinValue) ? DateTime.Now : enteredDate;	0
1590157	1590140	How should I combine two paths including backwards relative paths?	Path.GetFullPath(Path.Combine(abs, rel))	0
1336582	1330352	C# Dictionary with ReaderWriterLockSlim	public class ReadWriteDictionary<K,V>\n{\n    private readonly Dictionary<K,V> dict = new Dictionary<K,V>();\n    private readonly ReaderWriterLockSlim rwLock = new ReaderWriterLockSlim();\n\n    public V Get(K key)\n    {\n        return ReadLock(() => dict[key]);\n    }\n\n    public void Set(K key, V value)\n    {\n        WriteLock(() => dict.Add(key, value));\n    }\n\n    public IEnumerable<KeyValuePair<K, V>> GetPairs()\n    {\n        return ReadLock(() => dict.ToList());\n    }\n\n    private V2 ReadLock<V2>(Func<V2> func)\n    {\n        rwLock.EnterReadLock();\n        try\n        {\n            return func();\n        }\n        finally\n        {\n            rwLock.ExitReadLock();\n        }\n    }\n\n    private void WriteLock(Action action)\n    {\n        rwLock.EnterWriteLock();\n        try\n        {\n            action();\n        }\n        finally\n        {\n            rwLock.ExitWriteLock();\n        }\n    }\n}\n\nCache["somekey"] = new ReadWriteDictionary<string,int>();	0
6473478	6473460	How to simplify usage of nullable booleans in C#	myControlState.Visible = myFoo.IsValid ?? false;	0
8149730	8149658	Can I find out if string to ANSI conversion will result in loss of data?	Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(strData)) == strData;	0
15065914	15065580	web client request caching issue in wp7 app	"?disablecache=" + Environment.TickCount	0
8097794	8097760	How to make Settings.settings data persistent	Properties.Settings.Default.Save();	0
25239787	25239321	How to save an excel as part of windows form application	if (File.Exists(Application.StartupPath + @"\Webcam1.xlsx"))\n{\n  //Do My stuff\n}	0
637365	637355	user object with TreeNode in C#	TreeNode node = CreateATreeNode();\nnode.Tag = myStateObject;	0
29215537	29215353	How to compute the average for every n number in a list	public List<double> Average(List<double> number, int nElement)\n    {\n        var currentElement = 0;\n        var currentSum = 0.0;\n\n        var newList = new List<double>();\n\n        foreach (var item in number)\n        {\n            currentSum += item;\n            currentElement++;\n\n            if(currentElement == nElement)\n            {\n                newList.Add(currentSum / nElement);\n                currentElement = 0;\n                currentSum = 0.0;\n            }\n        }\n        // Maybe the array element count is not the same to the asked, so average the last sum. You can remove this condition if you want\n        if(currentElement > 0)\n        {\n            newList.Add(currentSum / currentElement);\n        }\n\n        return newList;\n    }	0
6893271	6893050	Copy one table to another based on criteria	DbCommand.CommandText = \n @"SELECT HIST.Field1, HIST.Field2, LOCINFO.Field3 FROM CAV_MBRHISTDEL AS HIST\n   INNER JOIN LOCINFODETL AS LOCINFO ON HIST.MBRNUM = LOCINFO.MBRNUM \n   WHERE LOCINFO.CYCLE = @CYCLE AND\n         LOCINFO.DISTRICT = @DISTRICT AND\n         HIST.BILLTYPE = '09' AND\n         HIST.BOLLMOYR <> '9999'";\n\nDbCommand.Parameters.AddWithValue("@CYCLE", cycle);\nDbCommand.Parameters.AddWithValue("@DISTRICT", district);	0
7594789	7594746	Managed analogue for SendMessage API function or How to send a message to window from C#?	[DllImport("user32.dll", CharSet = CharSet.Auto)]\nstatic extern IntPtr SendMessage(IntPtr hWnd, UInt32 Msg, IntPtr wParam, IntPtr lParam);\n\nprivate void button1_Click(object sender, EventArgs e)\n{\n    SendMessage(this.Handle, COMMAND_HERE, PARAM_HERE, 0);\n}	0
6763136	6763074	SQL Editing on Parameter	da.UpdateCommand = new OleDbCommand(string.Format("UPDATE tbl_Orders SET {0} = @myCell WHERE oid = @myIndex", myColumn), cs);	0
8601219	8601130	How to write the multi insert Statment in one store procedure	CREATE PROC pSomething (@params) AS     \nBEGIN..<code here>..END	0
3802555	3802542	how do convert string to byte[] in C#	Encoding.UTF8.GetBytes("abcd");	0
6762575	6760374	Merging DataTables - disregarding the first row	var dt1 = new DataTable("Test");\ndt1.Columns.Add("id", typeof(int));\ndt1.Columns.Add("name", typeof(string));\n\nvar dt2 = new DataTable("Test");\ndt2.Columns.Add("id", typeof(int));\ndt2.Columns.Add("name", typeof(string));\n\ndt1.Rows.Add(1, "Apple"); dt1.Rows.Add(2, "Oranges");\ndt1.Rows.Add(3, "Grapes");\ndt1.AcceptChanges();\n\ndt1.Rows[0].Delete();\ndt2.Merge(dt1);\ndt2.AcceptChanges(); \ndt1.RejectChanges();	0
22591893	22589914	Add Control to ASP.NET Web Page with runatserver	public void SetIdToHiddenField(string id)\n{\nPage.ClientScript.RegisterHiddenField("idHiddenField", id);\n}	0
33569439	33568818	Parts of a nested if statement not being reached	Optimize code	0
32672664	32672372	Storing names in array and displaying them in alphabetical order	string[] nameArray = new string[5];\n\nvoid CopyTextBoxesToArray()\n{\n    nameArray[0] = textBoxName1.Text;\n    nameArray[1] = textBoxName2.Text;\n    nameArray[2] = textBoxName3.Text;\n    nameArray[3] = textBoxName4.Text;\n    nameArray[4] = textBoxName5.Text;\n}\n\nprivate void button9_Click(object sender, EventArgs e)\n{\n    CopyTextBoxesToArray();\n    Array.Sort(nameArray);\n\n    foreach(string s in nameArray)\n    {\n        richTextBox1.Text += s + " ";\n    }\n}	0
16902671	16902614	Foreach loop performing reduntant logic	// (shared variables here)\n\nforeach (KeyValuePair<string, int> total in totalOrders)\n{\n    // Code relevant to all orders here\n}\n\nforeach (KeyValuePair<string, int> error in errorOrders)\n{\n    // Code relevant to erroneous orders only here\n}	0
18513516	18513361	How to use Ternary operation for Linq insertion from form Correctly	return rbReturning.SelectedItem == null ? null : rbReturning.SelectedItem.Text;	0
115905	115868	How do I get the title of the current active window using c#?	[DllImport("user32.dll")]\nstatic extern IntPtr GetForegroundWindow();\n\n[DllImport("user32.dll")]\nstatic extern int GetWindowText(IntPtr hWnd, StringBuilder text, int count);\n\nprivate string GetActiveWindowTitle()\n{\n    const int nChars = 256;\n    StringBuilder Buff = new StringBuilder(nChars);\n    IntPtr handle = GetForegroundWindow();\n\n    if (GetWindowText(handle, Buff, nChars) > 0)\n    {\n        return Buff.ToString();\n    }\n    return null;\n}	0
8179264	8179238	C# How to test if IPAddress is in a subnet?	IPAddress.Address	0
8075830	8075707	Making a dialog box stay in view	var dialogForm = new MyNewForm();\nif (dialogForm.ShowDialog() != DialogResult.OK)\n{\n   Application.Exit()\n}\nelse \n{\n   var pw = dialogForm.GetText(); // string var pw stores the enterd pw now\n   // validate your password here\n\n   if (PasswordIsCorrect())\n   {\n      // some logic here\n   } \n}	0
31368798	31368751	Func<t, bool> vs Manually expression performance in C# lambda	public List<User> GetUsers(Expression<Func<User, bool>> where)\n{\n    return _entity.Where(where).ToList();\n}\nvar users = _acc.GetUsers(x => x.Id == 1);	0
12179433	12178099	How to make server only functions in SignalR	public class Notifier\n    {\n        public static void Say(string message)\n        {\n            var context = GlobalHost.ConnectionManager.GetHubContext<MyHub>();\n            context.Clients.say(message);\n        }\n    }\n}	0
4264740	4264050	How to access other controls values in ITemplate?	[TemplateInstance(TemplateInstance.Single)]	0
11431349	11428114	Programmatically add Site Users Web Part	MembersWebPart membersWebPart = new MembersWebPart();\n                membersWebPart.DisplayType = MembersWebPartDisplayType.WebUserGroups;\n                membersWebPart.Title = "Anv?ndare och grupper";\n\n                wpManager.AddWebPart(membersWebPart, "Right", 2);	0
3827860	3827578	Populating Domain Objects from XML using LINQ to XML	var listing = \nxDoc.Elements("Listings")\n.Elements("Listing")\n.GroupBy (x => new { \n                ID = x.Element(XName.Get("CatID")).Value\n                , Description = x.Element(XName.Get("CatDesc")).Value\n            }\n)\n.Select (x => new Category { \n                ID = x.Key.ID\n                , Description = x.Key.Description\n                , Items = x.Select (i => new Item { \n                                    ID = i.Element("ItemID").Value\n                                    , Description = i.Element("ItemDesc").Value\n                                    , TotalPrice = decimal.Parse(i.Element("TotalPrice").Value) \n                                   }\n                    ).ToList()\n            }\n        )\n.OrderBy (x => x.ID);	0
10725840	10725786	how to extract file names with .txt from a text?	var filesnames = text.Split(new char[] { }) // split on whitespace into words\n                     .Where(word => word.EndsWith(".txt"));	0
33072801	33072162	How do I simplify component registration using Autofac	var dataAccess = Assembly.GetExecutingAssembly();\n\nbuilder.RegisterAssemblyTypes(dataAccess)\n   .Where(t => t.Name.EndsWith("Query"))\n   .AsImplementedInterfaces();	0
19496823	19037836	Is it possible to abandon/abort a RadAjaxRequest that is still processing when a new request is made?	radAjaxManager1.RequestQueueSize = 0;	0
16734720	16734567	get assembly of method	string assemblyName = this.GetType().Assembly.FullName;	0
28900963	28900745	How to make a method work in a period of time in C# Unity	if(SpeedboostTimeRemaining > 0)\n{\n    SpeedboostTimeRemaining -= Time.deltaTime\n    if(SpeedboostTimeRemaining < 0)\n    {\n        SpeedboostTimeRemaining = 0;\n        Player0.speed = 3.5f;\n    }\n}	0
6629454	6628427	dynamically append multiple linq expressions at run-time	foreach (Criteria.SegmentCriteria x in myCriteria)\n            {\n                Criteria.SegmentCriteria item = x;\n                if (myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAll)\n                {\n                    predicate = predicate.Expand().And<Segment>(CreateCriteriaExpression(item).Expand());\n                    customPropertiesPredicate = customPropertiesPredicate.Expand().And<Segment>(CreateCriteriaExpressionForCustomProperties(item).Expand());\n                }\n                else if (myMatchMethod == Common.MultipleCriteriaMatchMethod.MatchOnAny)\n                {\n                    predicate = predicate.Expand().Or<Segment>(CreateCriteriaExpression(item).Expand());\n                    customPropertiesPredicate = customPropertiesPredicate.Expand().Or<Segment>(CreateCriteriaExpressionForCustomProperties(item).Expand());\n                }\n            }	0
25116773	25116705	Insert date using c# in MS Access	insert into tbl_date(date_value) values(#7/8/2014#)	0
1127282	1127234	Do special processing for a type in a generic class	interface ISomething\n{\nvoid DoSomething();\n}\n\nclass NormalType : ISomething\n{\n// ...\npublic void DoSomething() { /* nothing to do */ }\n}\n\nclass SpecialType : ISomething\n{\n// ...\npublic void DoSomething() { this.SpecialString = "foo" }\n}\n\nclass MyGenericClass : ICloneable\n{\nprivate ISomething m_storedClass;\n\nprivate DoStuff()\n{\n// ...\nm_storedClass.DoSomething();\n}\n}	0
9295889	9295220	How is it possible to load jquery files after a specific update panel has been loaded?	var prm = Sys.WebForms.PageRequestManager.getInstance();\n\nprm.add_initializeRequest(InitializeRequest);\nprm.add_endRequest(EndRequest);\n\nfunction InitializeRequest(sender, args) {     \n}\n\nfunction EndRequest(sender, args) {\n  // here you can load your scripts.\n}	0
19347518	19347199	How to retrieve a single value from a listview	var obj=lvUsers.SelectedItems[0] as User;\nif(obj!=null)\n{\n   var age=obj.Age;\n}	0
29785768	29785380	Running Excel macro in a specific workbook fails from C#	string macro = string.Format("'{0}'!{1}", workbook.Name, macroName);\nApplication.Run(macro);	0
31623653	31623397	check phone number in a object class	bool isValid = Regex.IsMatch(value, @"/d{3}-/d{3}-/d{4}");	0
25521492	25521270	how to create a zero button in calculator in windows form calculator	case "zeroBtn":\nif(textBox_output.Text.IndexOf(".") > 0)\n{\n    textBox_output.Text+="0";\n}\nelse\n{\n    //edit: thanks for the comment\n    if(textBox_output.Text.ToString() == "")\n    {\n         textBox_output.Text+="0";\n    }\n    else if(!textBox_output.Text.StartWith("0"))\n    {\n        textBox_output.Text+="0";\n    }\n    else\n    {\n        //do nothing\n    }\n}	0
30117242	29889401	RadDock change background telerik winforms controls	radDock1.SplitPanelElement.Fill.BackColor = Color.Red;\n    radDock1.SplitPanelElement.Fill.GradientStyle = GradientStyles.Solid;\n\n    radDock1.MainDocumentContainer.SplitPanelElement.Fill.BackColor = Color.Yellow;\n    radDock1.MainDocumentContainer.SplitPanelElement.Fill.GradientStyle = GradientStyles.Solid;	0
9697352	9697310	Any of the properties equals any of a list of objects	var searchForIds = searchFor.Select(x => x.ID).ToList();\nvar query = context.Products\n                   .Where(product => product.Categories\n                                     .Any(cat => searchForIds.Contains(cat.ID)));	0
2386079	2383525	.NET Regex query to find only ONE new line	string[] strArray = Regex.Split(content, "(\r\n)*");	0
606373	606270	Launching a C# dialog from an unmanaged C++ mfc active x dll	[ComVisible(true)]\n[Guid("babe87fc-1467-4913-a1d3-47eeedf1afb5")]\npublic interface IDialogFactory {\n  void Create(); \n}	0
9638743	9626308	Is it possible to alter a DataServiceQuery after it has been constructed?	DemoService ctx = new DemoService(new Uri("http://services.odata.org/OData/OData.svc/"));\nDataServiceQuery<Product> products = ctx.Products;\n\nDataServiceQuery<Product> q = (DataServiceQuery<Product>)products.Where(p => p.Name == "Bread").Skip(10);\nMethodCallExpression skipCall = (MethodCallExpression)q.Expression;\nq = (DataServiceQuery<Product>)q.Provider.CreateQuery<Product>(skipCall.Arguments[0]);\nConsole.WriteLine(q);	0
2887007	2886966	Effective way of String splitting	static void Main(string[] args)\n{\n    string str = @"N:Pay in Cash++RGI:40++R:200++T:Purchase++IP:N++IS:N++PD:PC++UCP:598.80++UPP:0.00++TCP:598.80++TPP:0.00++QE:1++QS:1++CPC:USD++PPC:Points++D:Y++E:Y++IFE:Y++AD:Y++IR:++MV:++CP:~ ~N:ERedemption++RGI:42++R:200++T:Purchase++IP:N++IS:N++PD:PC++UCP:598.80++UPP:0.00++TCP:598.80++TPP:0.00++QE:1++QS:1++CPC:USD++PPC:Points++D:Y++E:Y++IFE:Y++AD:Y++IR:++MV:++CP:"; \n    System.Text.RegularExpressions.MatchCollection MC = System.Text.RegularExpressions.Regex.Matches(str,@"((RGI|N):.*?)\+\+");\n    foreach( Match Foundmatch in MC)\n    {\n        string[] s = Foundmatch.Groups[1].Value.Split(':');\n        Console.WriteLine("Key {0} Value {1} " ,s[0],s[1]);\n\n    }\n\n}	0
6141933	6141723	Add a collection to a view model List	var query = from p in data.GetMember \n            where (p.Client == client && p.Person_id == pid) \n            select new MemberCommunicationType \n                       { person_id = p.person_id, comm_id = p.comm_id}\n            ;\nvar output = new GetMemberColl { memberCommunication = query.ToArray() };	0
24108584	24108479	Attach decimal part to an integer	var total = Double.Parse(string.Concat(left, ",", right));	0
1528967	1528958	Convert a IList<int> collection to a comma separated list	IList<int> list = new List<int>( new int[] { 1, 2, 3 } );\n    Console.WriteLine(string.Join(",", list.Select( i => i.ToString() ).ToArray( )));	0
22576951	22576859	How do i upload text file to my ftp every minute?	FtpWebRequest ftpClient = (FtpWebRequest)FtpWebRequest.Create(new Uri(ftpurl + \n                                            ftpusername + "_" + filename));	0
3785720	3785695	How to get the referred string of an Action<string> delegate?	Expression<Action<string>>	0
21827118	21518163	TPL Dataflow: design for parallelism while keeping order	public Task CreateAnimationFileAsync(IEnumerable<Bitmap> frames)\n{\n    var frameProcessor = new TransformBlock<Bitmap, Bitmap>(\n        frame => ProcessFrame(frame),\n        new ExecutionDataflowBlockOptions\n        { MaxDegreeOfParallelism = DataflowBlockOptions.Unbounded });\n\n    var animationWriter = new ActionBlock<Bitmap>(frame => WriteFrame(frame));\n\n    frameProcessor.LinkTo(\n        animationWriter,\n        new DataflowLinkOptions { PropagateCompletion = true });\n\n    foreach (var frame in frames)\n    {\n        frameProcessor.Post(frame);\n    }\n\n    frameProcessor.Complete();\n\n    return frameProcessor.Completion;\n}\n\nprivate Bitmap ProcessFrame(Bitmap frame)\n{\n    ???\n}\n\nprivate async Task WriteFrame(Bitmap frame)\n{\n    ???\n}	0
23905874	20858141	Keyboard won't dismiss even after Focus change	TextBox.KeyDown += (s, a) => {\n if (a.Key == VirtualKey.Enter) {\n   TextBox.IsEnabled = false;\n   TextBox.IsEnabled = true;\n }	0
25528037	25518485	How To Create Custom Route in MVC	using System.Web.Mvc;\n\nnamespace WebApplication1.Areas.Admin\n{\n    public class AdminAreaRegistration : AreaRegistration \n    {\n        public override string AreaName \n        {\n            get \n            {\n                return "Admin";\n            }\n        }\n\n        public override void RegisterArea(AreaRegistrationContext context) \n        {\n            // This is where the custom route has to be registered for me to access\n            // it from my area.\n            context.MapRoute(\n                "Admin_pages",\n                "Admin/Pages/{action}/{id}",\n                new { action = "Index", \n                      controller = "CMSPages", \n                      id = UrlParameter.Optional }\n            );\n\n            context.MapRoute(\n                "Admin_default",\n                "Admin/{controller}/{action}/{id}",\n                new { action = "Index", id = UrlParameter.Optional }\n            );\n        }\n    }\n}	0
3421744	3421709	byte array to double conversion in c#	var myBytes[] = {0,0,0,0,0,1,1,2}; //assume you pad your array with enough zeros to make it 8 bytes.\nvar myDouble = BitConverter.ToDouble(myBytes,0);	0
27395819	27395750	How to add item to IEnumerable<T> in Workflow?	[DataMember]\npublic virtual List<Account> TargetAccounts { get; set; }	0
5487929	5487882	Linq - Left outer join with dot notation	var query2 = db.Users.GroupJoin(db.Defects,\n                                u => u.userId,\n                                d => d.userID,\n                                (u, defectsGroup) => new { u, defectsGroup})\n                     .SelectMany(z => z.defectsGroup.DefaultIfEmpty(),\n                                 (z, d) => new { z.u, d });	0
967370	967361	Is accepting Object as a parameter acceptable?	public bool IsValidSSN(object ssn) {\n  ...\n  IsValidSSN(Convert.ToInt32(ssn));\n  ...\n}\n\npublic bool IsValidSSN(int ssn) {\n  ...\n}	0
4422302	4422250	Get static property by string	PropertyInfo propertyInfo = typeof(MyClass).GetProperty("something");\nstring something = (string) propertyInfo.GetValue(null, null);	0
28690494	28690220	Get information from button	private void btn_Clicked(object sender, RoutedEventArgs e)\n{\n    Button cmd = (Button)sender;\n    string name = cmd.name;\n    switch(name)\n    //{ do some stuff based on the button name}\n}	0
17235224	16896399	Best practice how to display/receive IP network camera stream	#include "cv.h"\n#include "highgui.h"\n#include <iostream>\n\nint main(int, char**) {\n    cv::VideoCapture vcap;\n    cv::Mat image;\n\n    const std::string videoStreamAddress = "rtsp://cam_address:554/live.sdp"; \n    /* it may be an address of an mjpeg stream, \n    e.g. "http://user:pass@cam_address:8081/cgi/mjpg/mjpg.cgi?.mjpg" */\n\n    //open the video stream and make sure it's opened\n    if(!vcap.open(videoStreamAddress)) {\n        std::cout << "Error opening video stream or file" << std::endl;\n        return -1;\n    }\n\n    int counter = 0;\n    for(;;) {\n        counter++;\n\n        if(!vcap.read(image)) {\n            std::cout << "No frame" << std::endl;\n            cv::waitKey();\n        }\n\n        // if the picture is too large, imshow will display warped images, so show only every 10th frame\n        if (counter % 10 != 0)\n            continue;\n\n        cv::imshow("Output Window", image);\n        if(cv::waitKey(1) >= 0) break;\n    }   \n}	0
9028087	9028029	How To Change DataType of a DataColumn in a DataTable?	DataTable dtCloned = dt.Clone();\ndtCloned.Columns[0].DataType = typeof(Int32);\nforeach (DataRow row in dt.Rows) \n{\n    dtCloned.ImportRow(row);\n}	0
22098205	22081297	Shutting down to PowerState S4	Process.Start("shutdown", "/s /f /hybrid /t 0");	0
510358	510341	Force subclasses of an interface to implement ToString	public abstract class Base\n{\n    public abstract override string ToString(); \n}	0
15904	15272	Aging Data Structure in C#	list.push_end(new_data)\nwhile list.head.age >= age_limit:\n    list.pop_head()	0
11688090	11687903	Could not find a part of the path on windows azure	LocalResource localResource = RoleEnvironment.GetLocalResource("DownloadedTemplates");	0
13942023	13941877	Methods to login to website via python for scraping	import requests\n    from requests_ntlm import HttpNtlmAuth\n\n    requests.get("http://ntlm_protected_site.com",auth=HttpNtlmAuth('domain\\username','password'))	0
32671685	32671438	Select specific cities from List	Console.WriteLine(cities.Distinct().Count());\nConsole.WriteLine(String.Join(", ", cities.Where(city=>city.IsOpenOnFriday).ToList()));	0
7200329	7200044	How to change the user control in WPF?	private void AddNewUserControlAndAutoRemoveOldUserControl(UserControl control)\n        {\n            if (control != null)\n            {\n                Panel parent = control.Parent as Panel;\n\n                if (parent != null)\n                {\n                    // Removing old UserControl if present\n                    if(parent.Children.Count > 0)\n                        parent.Children.RemoveAt(0);\n\n                    parent.Children.Insert(0, control);\n                }\n            }\n        }\n}	0
20374445	20374414	Actioning a C# GUI from beneath	this.Controls.Add	0
3199190	3199158	C# regular expression to strip all but alphabetical and numerical characters from a string?	var result = Regex.Replace(input, @"[^a-zA-Z0-9]", "");	0
20080354	20080112	How to save and load the contents of multiple text boxes in C#?	private void Save(object sender, EventArgs args)\n{\n   //Gather text info e.g.: var myText1 = myTextBox1.Text;\n   //Save to the database or wherever using Stream \n   //or SqlConnection or something else.  See below\n}	0
20474850	20474357	configure mercurial .hgingore to ignore all files and folder in a directory except 'repositories.config'	.hgignore	0
12694244	12694136	Windows Phone - Storyboard TargetName in runtime	Storyboard.SetTargetProperty(keyFrameDa, new PropertyPath(PlaneProjection.RotationXProperty));\nStoryboard.SetTarget(keyFrameDa, cardBack.Projection);	0
28586129	28585870	Call a method only after jobs on other threads have terminated?	async private void loadData_Click_1(object sender, EventArgs e)\n{\n    await Task.WhenAll(Task.Run(() => loadData()), \n                       Task.Run(() => loadOtherData()));\n\n    updateGrids(myDictionary); \n}	0
33127388	33127301	WPF - Load image stored in another dll	var bitmap = new BitmapImage(\n    new Uri("pack://application:,,,/GameTools;component/Images/face1.png"));	0
4739869	4739795	How can I test for negative zero?	private static readonly long NegativeZeroBits =\n    BitConverter.DoubleToInt64Bits(-0.0);\n\npublic static bool IsNegativeZero(double x)\n{\n    return BitConverter.DoubleToInt64Bits(x) == NegativeZeroBits;\n}	0
971440	970779	How To Draw a Model in XNA with the BasicEffect	private void DrawModel(Model m)\n{\n    Matrix[] transforms = new Matrix[m.Bones.Count];\n    float aspectRatio = graphics.GraphicsDevice.Viewport.Width / graphics.GraphicsDevice.Viewport.Height;\n    m.CopyAbsoluteBoneTransformsTo(transforms);\n    Matrix projection = Matrix.CreatePerspectiveFieldOfView(MathHelper.ToRadians(45.0f),\n        aspectRatio, 1.0f, 10000.0f);\n    Matrix view = Matrix.CreateLookAt(new Vector3(0.0f, 50.0f, Zoom), Vector3.Zero, Vector3.Up);\n\n    foreach (ModelMesh mesh in m.Meshes)\n    {\n        foreach (BasicEffect effect in mesh.Effects)\n        {\n            effect.EnableDefaultLighting();\n\n            effect.View = view;\n            effect.Projection = projection;\n            effect.World = gameWorldRotation * transforms[mesh.ParentBone.Index] * Matrix.CreateTranslation(Position);\n        }\n        mesh.Draw();\n    }\n}	0
7413510	7413466	How can I get the baseurl of site?	string baseUrl = Request.Url.Scheme + "://" + Request.Url.Authority + \n    Request.ApplicationPath.TrimEnd('/') + "/";	0
18029714	18029580	Convert String "7/16/2013 7:00:00 AM" to DateTime	var dt = DateTime.ParseExact("7/16/2013 7:00:00 AM", "M/d/yyyy h:mm:ss tt", CultureInfo.InvariantCulture);	0
12261857	12261696	How do I pass a custom class to a WCF service?	[DataContract]\npublic class Person\n{\n    [DataMember]\n    public int id { get; set; }\n\n    [DataMember]\n    public string Name{ get; set; }\n}	0
10743261	10743067	XML serialization array in C#	public class Items\n{\n    [XmlAttribute("id")]\n    public string ID { get; set; }\n\n    [XmlAttribute("title")]\n    public string Title { get; set; }\n\n    [XmlElement("word")]\n    public List<string> Words { get; set; }\n}\n\n[XmlRoot("root")]\npublic class Lists\n{\n    [XmlElement("list")]\n    public List<Items> Get { get; set; }\n}	0
3109132	3109009	How to make a DataTable from DataGridView without any Datasource?	DataTable dt = new DataTable();\nforeach(DataGridViewColumn col in dgv.Columns)\n{\n   dt.Columns.Add(col.HeaderText);    \n}\n\nforeach(DataGridViewRow row in dgv.Rows)\n{\n    DataRow dRow = dt.NewRow();\n    foreach(DataGridViewCell cell in row.Cells)\n    {\n        dRow[cell.ColumnIndex] = cell.Value;\n    }\n    dt.Rows.Add(dRow);\n}	0
20425396	20425320	How to get application name in WPF	icon.UriSource = new Uri(string.Format(\n    "pack://application:,,,/{0};component/Images/logo.ico",\n    Path.GetFileNameWithoutExtension(Application.ResourceAssembly.Location)));	0
33686837	33654620	Using Ninject in two projects in one solution, a cyclical dependency exception	_kernel\n    .Bind<DefaultModelValidatorProviders>()\n    .ToConstant(new DefaultModelValidatorProviders(\n         config.Services.GetServices(\n             typeof (ModelValidatorProvider))\n         .Cast<ModelValidatorProvider>()));	0
7255355	7255345	Remove a row from a DataTable within a DataSet	for(int i = dsData.Tables["TAble1"].Rows; i > 0; i--)\n{\n     if(item.SubItems[2].Text == dsData.Tables["Table1"].Rows[i - 1]["LoginName"].ToString())\n         dsData.Tables["Table1"].Rows.Remove(i - 1)\n}	0
20387602	20387477	How to calculate property in a chained linq query	List<Developer> developers =\n    employees.Where(x => x.Department == "Dev")\n             .Select(x => new Developer\n             {\n                 Name = x.Name,\n                 Department = x.Department,\n                 JobTitle = x.Function,\n                 Division = String.Concat(x.Function, "/", x.Department)\n             }).ToList();\n\n    return developers;	0
22022197	21762724	C# Get members of Generic object	for (int i = 0; i < c.Count; i++)\n        {\n            System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(c[i].GetType());\n            using (StringWriter writer = new StringWriter())\n            {\n                x.Serialize(writer, c[i]);\n                String details = writer.ToString();\n            }\n                   //do here what ever you want\n        }	0
24887423	24887091	why do I have to match the parameter name to get json data from ajax call in MVC4 web app?	[HttpPost]\npublic ActionResult DATACRUD()\n{\n    Stream req = Request.InputStream;\n    req.Seek(0, System.IO.SeekOrigin.Begin);\n    string json = new StreamReader(req).ReadToEnd();\n    return Json(new { fromMVC = json });\n}	0
13271650	13271347	Xsd documentation value	annotation.Items.Add(doc);\ndoc.Markup = TextToNodeArray("Your text you need");	0
26309485	26309375	Assigning text to buttons Via methods	private void button1_Click(object sender, EventArgs e)\n {\n     var button = (Button) sender;\n     button.Text = "X";\n }	0
1366422	1366395	Form without a border style	public partial class Form1 : Form {\n    protected override CreateParams CreateParams {\n        get {\n            CreateParams par = base.CreateParams;\n            par.Style = par.Style | 0x20000; // Turn on the WS_MINIMIZEBOX style flag\n            return par;\n        }\n    }\n}	0
1309	1304	How to check for file lock?	if not locked then\n    open and update file	0
17418513	17418367	How to use foreach in c#?	for (int i = 0; i < customer.Count; i++)	0
3046672	3046665	How do I keep the 0's in a Date	string s = DateTime.Now.ToString("MM/dd/yyyy");	0
13037465	13037388	Allowing numbers from 1 to 100 with EditorFor	(100|([1-9][0-9])|[1-9]	0
4302143	4302130	Loading user controls dynamically	Control ctrl = Page.LoadControl("UserControlPath");\ndivControls.Controls.Clear();\ndivControls.Controls.Add(ctrl);	0
16162547	16162433	How to replace tag names in XML file using C#?	one.SetAttributeValue("name", "ID");	0
25127981	25127273	Wrting a SQL query in LINQ	var group_key = (from g in this.Context.Groups\n            where g.ID == groupID\n                  && g.TaxId == groupTaxId\n            select g.Group_K);\n\n        var query = (from a in this.Context.Addresses\n            join ga in this.Context.GroupAddress on a.Address_K equals ga.Address_K\n            where (group_key.Contains(ga.Group_K) && a.ZipCode == "whatever passed from method" && ga.Address_Type == "whatever passed from your method")\n            select a);	0
5406226	4332885	Sync with Google Calendar both ways	string formatedDate = "";\n        EventQuery query = new EventQuery();\n        DateTime? time;\n        if (!string.IsNullOrEmpty(startDate))\n        {\n            time = Convert.ToDateTime(startDate);\n            formatedDate = string.Format("{0:s}", time);\n\n            // Create the query object:\n            query.Uri = new Uri("http://www.google.com/calendar/feeds/" + service.Credentials.Username + "/private/full?updated-min=" + formatedDate);\n        }\n        else\n        {\n            query.Uri = new Uri("http://www.google.com/calendar/feeds/" + service.Credentials.Username + "/private/full");\n        }\n\n\n        // Tell the service to query:\n        EventFeed calFeed = service.Query(query);\n        return calFeed.Entries.Cast<EventEntry>();	0
18312573	18312276	Add properties to an object with reflection in c #	protected dynamic getNewObject(String name, String phone, String email)\n    {\n\n\n        // ... //I can not add the variables that received by the object parameter here.\n        dynamic ex = new ExpandoObject();\n        ex.Name = name;\n        ex.Phone = phone;\n        ex.Email = email;\n        return ex;\n    }\n\n    private void button1_Click_2(object sender, EventArgs e)\n    {\n        var ye = getNewObject("1", "2", "3");\n        Console.WriteLine(string.Format("Name = {0},Phone = {1},Email={2}", ye.Name, ye.Phone, ye.Email));\n    }	0
2272500	2272476	How to convert a generic List<T> to an Interface based List<T>	allShapes = cubes.Cast<Shape>().ToList();	0
5571522	5571485	Converting Decimal to Double in C#?	decimal x  = 3.141592654M ;\ndouble  pi = (double) x ;	0
5942689	5942612	Combine complete URL and virtual URL, like a browser does	Uri combined = new Uri(\n  new Uri("http://www.domain.com/aaa/bbb/ccc/ddd/eee.ext", UriKind.Absolute),\n  "../../fff.ext"\n);	0
4868459	4868402	How can a standard error icon be shown in on a C# windows forms dialog?	Bitmap b = SystemIcons.Error.ToBitmap();	0
20690988	20690961	Display text in a view	Book Name: @Html.DisplayFor(model =>  model.Book.Name)	0
23310888	22732926	Caliburn.micro with multiple ViewModels	Conductor<T>.Collection.AllActive	0
31110984	31110652	LINQ index of min value of one Property of a Custom Object c#	int minPrice = closingsBook.Min(book => book.LimitPrice);\n\nvar indexes = closingsBook.Select((book, index) => new { book, index })\n             .Where(x => x.book.LimitPrice== minPrice)\n             .Select(x => x.index);	0
27395852	27395584	Getting path from lambda expression	string PropertyName<T>(Expression<Func<T>> expression)\n    {\n        var body = expression.Body as MemberExpression;\n\n        if (body == null)\n        {\n            body = ((UnaryExpression)expression.Body).Operand as MemberExpression;\n        }\n\n        return string.Join(".", GetPropertyNames(body).Reverse());\n    }\n\n    private IEnumerable<string> GetPropertyNames(MemberExpression body)\n    {\n        while (body != null)\n        {\n            yield return body.Member.Name;\n            var inner = body.Expression;\n            switch (inner.NodeType)\n            {\n                case ExpressionType.MemberAccess:\n                    body = inner as MemberExpression;\n                    break;\n                default:\n                    body = null;\n                    break;\n\n            }\n        }\n    }	0
23110025	23091054	GridView with HyperLinkField prevent select	protected override void Render(HtmlTextWriter writer)\n    {\n        foreach (GridViewRow row in this.Rows)\n            if (row.RowType == DataControlRowType.DataRow)\n                foreach (DataControlFieldCell cell in row.Cells)\n                    if ((cell.ContainingField).HeaderText != "Detalhes")\n                        cell.Attributes["onclick"] = this.Page.ClientScript.GetPostBackClientHyperlink(this, string.Format("Select${0}", row.RowIndex), true);\n\n        base.Render(writer);\n    }	0
914904	882683	Watin - Handling Confirm Dialogs with ConfirmDialogHandler	using (new UseDialogOnce(ie.DialogWatcher, approveConfirmDialog))\n        {\n            ie.Button(Find.ByName("btn")).ClickNoWait();\n            approveConfirmDialog.WaitUntilExists();\n            approveConfirmDialog.OKButton.Click();\n            ie.WaitForComplete();\n        }	0
10990474	10990277	How to make animation awaitable?	public Task Foo()\n{\n    var tcs = new TaskCompletionSource<bool>();\n    storyboard.Begin();\n    storyboard.Completed += (s, e) => tcs.SetResult(true);\n    return tcs.Task;\n}	0
14877869	14875232	How to clip some part TeeChart image	public Form1()\n{\n  InitializeComponent();\n  InitializeChart();\n}\n\nprivate Bitmap chartBmp;\n\nprivate void InitializeChart()\n{\n  tChart1.Series.Add(new Steema.TeeChart.Styles.Bar()).FillSampleValues();\n\n  chartBmp = tChart1.Bitmap;\n\n  tChart1.GetLegendRect += tChart1_GetLegendRect;\n}\n\nvoid tChart1_GetLegendRect(object sender, Steema.TeeChart.GetLegendRectEventArgs e)\n{\n  Rectangle cropRect = e.Rectangle;\n  Bitmap legendImg = new Bitmap(cropRect.Width, cropRect.Height);\n\n  using (Graphics g = Graphics.FromImage(legendImg))\n  {\n    g.DrawImage(chartBmp, new Rectangle(0, 0, legendImg.Width, legendImg.Height),\n                     cropRect,\n                     GraphicsUnit.Pixel);\n  }\n\n  legendImg.Save(@"c:\temp\legend.png");\n}	0
17116113	17115369	Creating an array from JSON	using (WebClient wc = new WebClient())\n{\n    string json = wc.DownloadString("http://moon.eastlink.com/~jandrews/webservice2.php");\n    var jObj = JObject.Parse(json);\n\n    var items = jObj.Children()\n                .Cast<JProperty>()\n                .Select(c => new\n                {\n                    Title = (string)c.Value["{\"Title"],\n                    Body = (string)c.Value["Body"],\n                    Caption = (string)c.Value["Caption"],\n                    Datestamp = (string)c.Value["Datestamp"],\n                })\n                .ToList();\n}	0
2697193	2697170	Start a process as LocalSystem using ProcessStartInfo	Process.Start()	0
26953286	26951490	Getting data from GridView after changing the DataSource	protected void GridView2_DataBound(object sender, EventArgs e)\n{\n    // Populate dropdown with column names\n    if(e.Row.RowType != DataControlRowType.Header) return; //only continue if this is hdr row\n    ddColumnSearch.Items.Clear();\n    foreach (TableCell cell in e.Row.Cells)\n    {\n        ddColumnSearch.Items.Add(new ListItem(cell.Text));\n    }\n}	0
20518586	20518491	Row filter crashes C# app with System.Data.EvaluateException was unhandled message	private void driverNo_TextChanged(object sender, EventArgs e)\n    {\n\n        if (string.IsNullOrEmpty(driverNo.Text))\n        {\n            ((DataTable)dataGridView1.DataSource).DefaultView.RowFilter = string.Empty;\n            return;\n        }\n\n        int _driverNo;\n\n        if (int.TryParse(driverNo.Text,out _driverNo))\n            ((DataTable)DataGridViews.DataSource).DefaultView.RowFilter = "DriverNo = " + _driverNo;\n        else\n            MessageBox.Show("Invalid driver no.");\n    }	0
26670489	26657827	Limit property to specific values	public class Item\n{\n    private readonly LimitedString _reality = new LimitedString("Real", "Imaginary", "Based on reality");\n    public string Reality\n    {\n        get { return _reality.Value; }\n        set { _reality.Value = value; }\n    }\n\n    private readonly LimitedString _colour = new LimitedString("Other", "Blue", "Red", "Green");\n    public string Colour\n    {\n        get { return _colour.Value; }\n        set { _colour.Value = value; }\n    }\n}	0
24712607	24712288	ASP.NET Controller adding 1 hour to date (format ISO 8601) sent in AJAX request	NewEventStart = NewEventStart.ToUniversalTime();	0
18524227	18473975	Return columns from identified in List<string> in linq select clause at runtime	var foundExcelRows =\nfrom excelRow in this.ExcelDataTable.AsEnumerable()\njoin file in this.FilesToImport.AsEnumerable()\non excelRow.Field<Guid>("ceGuid") equals file.SourceFileIdentifier\nselect excelRow;\n\nfor (int i = 0; i < foundExcelRows.Count(); i++)\n{\n    DataRow row = foundExcelRows.ElementAt(i);\n    // work with this row since I know the columns I expect   \n}	0
13926153	13926111	comparing multiple items in the same list	PList = PList.GroupBy (x => x.Name).SelectMany (x=>x.OrderBy(y=> y.Date).Take(1))	0
33781669	33781109	Call to controller action keeps running -after- execution	this.Manager.CheckName(dossierId, id)	0
20501764	20501450	How to use linq contains like %[0-9]%	var result = partNumbers.Where(x => Regex.Match(x, "\\d+").Success);	0
16823317	16823087	Windows Phone string to color	public static Color GetColor(String ColorName)\n{\n    Type colors = typeof(System.Windows.Media.Colors);\n    foreach(var prop in colors.GetProperties())\n    {\n        if(prop.Name == ColorName)\n            return ((System.Windows.Media.Color)prop.GetValue(null, null));\n    }\n\n    throw new Exception("No color found");\n}	0
22543909	22541788	Print Preview of multiple pages not working	printDocument1.PrintPage += this.printDocument1_PrintPage;	0
9702592	9687277	Selected value of dropdownlist in repeater control - with predefined items	protected void rpt_ItemDataBound(object sender, RepeaterItemEventArgs e)\n    if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)\n    {\n        DropDownList cbo = (DropDownList)e.Item.FindControl("cboType");\n        Behaviour b = (Behaviour)e.Item.DataItem;\n\n        for (int i = 0; i < cbo.Items.Count; i++)\n        {\n            if (b.Type_of_Behaviour == cbo.Items[i].Value)\n                cbo.Items[i].Selected = true;\n            else\n                cbo.Items[i].Selected = false;\n        }\n    }\n}	0
4214162	4214045	Using Regex to extract table names from a file containing SQL queries	(?<=from|join)(\s+\w+\b)	0
2267007	2266837	How to restrict access to USB drives using C#?	using Microsoft.Win32;\nRegistryKey key;\nkey = Registry.LocalMachine.OpenSubKey\n         ("SYSTEM\\CurrentControlSet\\Services\\UsbStor");\nkey.SetValue("Start", 4, RegistryValueKind.DWord);  //disables usb drives\nkey.SetValue("Start", 3, RegistryValueKind.DWord);  //enables usb again	0
20806557	20800310	WPF TreeView with CheckBox - How to Get the list of Checked?	private IEnumerable<TreeViewModel> GetCheckedItems(TreeViewModel node)\n{\n    var checkedItems = new List<TreeViewModel>();\n\n    ProcessNode(node, checkedItems);\n\n    return checkedItems;\n}    \n\nprivate void ProcessNode(TreeViewModel node, IEnumerable<TreeViewModel> checkedItems)\n{\n    foreach (var child in node.Children)\n    {\n        if (child.IsChecked)\n            checkedItems.Add(child);\n\n        ProcessNode(child, checkedItems);\n    }\n}	0
4733077	4723322	DES encoding with security key C#	private static byte[] Encrypt(byte[] value, byte[] key)\n    {\n        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider\n                                                      {\n                                                          Mode = CipherMode.ECB,\n                                                          Padding = PaddingMode.None\n                                                      };\n\n        MemoryStream memoryStream = new MemoryStream();\n\n        CryptoStream cryptoStream = new CryptoStream(memoryStream, cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);\n\n        cryptoStream.Write(value, 0, value.Length);\n        cryptoStream.Close();\n\n        return memoryStream.ToArray();\n    }	0
24088239	24088203	Reusing lambda expression	public class MyProjectionExpressions\n {\n    public static Expression<Func<Log, dynamic>> LogSelector()\n    {\n        return log => new\n        {\n            logId = log.LogId,\n            message = log.Message,\n        };\n    }\n\n    //Get the expression as a Func<Log, dynamic>, then apply it\n    //to your log object.\n    private static Func<Log, dynamic> impl = LogSelector().Compile();\n\n    public static dynamic LogSelector(Log log)\n    {\n        return impl(log);\n    }\n }	0
11536362	11535293	populate CheckBoxList from query using FindByValue	grades.DataBind();	0
5119534	5119509	How To Get A Value Out Of A DetailsView DataItem Property	Datetime myDate=(DateTime)((DataRowView)dv.DataItem)["_DTMON_F"];	0
27676892	27265110	Can you derive an action using Generics for use with TypeMock WhenCalled	public void RegisterFakeData<T> (Context ctx,IEnumerable<T> list)\n        {\n            var name =typeof (T).Name;\n            var mi = ctx.GetType().GetProperty(name).GetGetMethod();\n            var args = new object[0] ;\n            Isolate.WhenCalled(() =>(IEnumerable<T>)mi.Invoke(ctx,args)).WillReturnCollectionValuesOf(list);\n        }	0
7272719	7272668	Linq & C# - Inserting distinct data from one class into another	List<Products> products = (from x in everythingList\n                          group x by new { x.Product, x.ProductName } into xg\n                          select new Products\n                          {\n                             Product = xg.Key.Product,\n                             ProductName = xg.Key.ProductName \n                          }).ToList();	0
22383152	22382546	How to insert operation through WCF Service with MYSQL?	[ServiceContract]\npublic interface IServiceClient\n{\n    [OperationContract]\n    void InsertMaster(Service ServiceObj);\n}\n\n[DataContract]\npublic class Service\n{\n    [DataMember]\n    public string Id;\n    [DataMember]\n    public string Submitter;\n    [DataMember]\n    public string Comments;\n    [DataMember]\n    public DateTime TimeSubmitted;\n}\n\npublic void InsertMaster(Service ServiceObj)\n{\n    string query = "INSERT INTO movies (id, submitter, comments, time) VALUES(ServiceObj.id, ServiceObj.submitter, ServiceObj.comments, ServiceObj.time)";\n    //open connection\n    connection.Open();\n    //create command and assign the query and connection from the constructor\n    MySqlCommand cmd = new MySqlCommand(query, connection);\n    //Execute command\n    cmd.ExecuteNonQuery();\n    //close connection\n    connection.Close();\n\n}	0
11678835	11632660	Add CSS Class through a Repeater	string currClass =  hc.Attributes["class"].ToString();\nstring count = e.Item.Controls.Count.ToString();\n        if (e.Item.ItemIndex == 0)\n                    {\n                        currClass += " TabbedPanelsTabSelected";\n                    }\n     else if (e.Item.ItemIndex.ToString() == count)\n                    {\n                        currClass += " last";\n                    }	0
20878314	20878047	Chart without Axis Lines	chartArea.AxisY.LineWidth = 0;\n        chartArea.AxisX.LineWidth = 0;\n        chartArea.AxisX.LabelStyle.Enabled = false;\n        chartArea.AxisY.LabelStyle.Enabled = false;\n        chartArea.AxisX.MajorTickMark.Enabled = false;\n        chartArea.AxisY.MajorTickMark.Enabled = false;	0
9260675	9257058	How Can I Use Parallel For in TPL instead of While	long _n;\nint _i;\nlong _mod;\n\nlong FindModulusParallel(long n, int i)\n{\n    _mod = _n = n;\n    _i = i;\n\n    var actions = Enumerable.Range(0, Environment.ProcessorCount)\n                            .Select<int,Action>(j => Subtract).ToArray();\n    Parallel.Invoke(actions);\n\n    return _mod;\n}\n\nvoid Subtract()\n{\n    while (Interlocked.Add(ref _n, -_i) >= 0)\n        Interlocked.Add(ref _mod, -_i);\n}	0
9163002	9162760	How to implement a lazy stream chunk enumerator?	public IEnumerable<BufferWrapper> getBytes(Stream stream)\n{\n    List<int> bufferSizes = new List<int>() { 8192, 65536, 220160, 1048576 };\n    int count = 0;\n    int bufferSizePostion = 0;\n    byte[] buffer = new byte[bufferSizes[0]];\n    bool done = false;\n    while (!done)\n    {\n        BufferWrapper nextResult = new BufferWrapper();\n        nextResult.bytesRead = stream.Read(buffer, 0, buffer.Length);\n        nextResult.buffer = buffer;\n        done = nextResult.bytesRead == 0;\n        if (!done)\n        {\n            yield return nextResult;\n            count++;\n            if (count > 10 && bufferSizePostion < bufferSizes.Count)\n            {\n                count = 0;\n                bufferSizePostion++;\n                buffer = new byte[bufferSizes[bufferSizePostion]];\n            }\n        }\n    }\n}\n\npublic class BufferWrapper\n{\n    public byte[] buffer { get; set; }\n    public int bytesRead { get; set; }\n}	0
20847880	20847738	How to know the name of the windows device in C#	string pcName = System.Environment.MachineName;	0
9324588	9324245	Have to refresh page twice for custom properties to affect databound controls	if(!IsPostBack)\n{\n  dg.DataSource = GetData();\n  dg.DataBind();\n}	0
19409301	19409009	C# Index of for space and next informations	//extract the first number found in the address string, wherever that number is.\nMatch m = Regex.Match(address, @"((\d+)/?(\d+))");\nstring numStr = m.Groups[0].Value;\n\nstring streetName = address.Replace(numStr, "").Trim();\n//if a number was found then convert it to numeric \n//also remove it from the address string, so now the address string only\n//contains the street name\nif (numStr.Length > 0)\n{\n    string streetName = address.Replace(numStr, "").Trim();\n    if (numStr.Contains('/'))\n    {\n        int num1 = Convert.ToInt32(m.Groups[2].Value);\n        int num2 = Convert.ToInt32(m.Groups[3].Value);\n    }\n    else\n    {\n        int number = Convert.ToInt32(numStr);\n    }\n}	0
17502336	17502142	Assigning indexes to buttons C#	--- loop ---\nButton abc = new Button();\nabc.Name = loopCounter.ToString();\n--- loop ---	0
7359955	7359923	Adding/summing two arrays	var a = new int[] {1,2,3 };\nvar b = new int[] {4,5,6 };\na.Zip(b, (x, y) => x + y)	0
30415250	30411667	How to detect mouse click on GUITexture in unity	public class RightButton : MonoBehaviour {\n\n    public Texture bgTexture;\n    public Texture airBarTexture;\n    public int iconWidth = 32;\n    public Vector2 airOffset = new Vector2(10, 10);\n\n\n    void start(){\n    }\n\n    void OnGUI(){\n        int percent = 100;\n\n        DrawMeter (airOffset.x, airOffset.y, airBarTexture, bgTexture, percent);\n    }\n\n    void DrawMeter(float x, float y, Texture texture, Texture background, float percent){\n        var bgW = background.width;\n        var bgH = background.height;\n\n        if (GUI.Button (new Rect (x, y, bgW, bgH), background)){\n            // Handle button click event here\n        }\n\n        var nW = ((bgW - iconWidth) * percent) + iconWidth;\n\n        GUI.BeginGroup (new Rect (x, y, nW, bgH));\n        GUI.DrawTexture (new Rect (0, 0, bgW, bgH), texture);\n        GUI.EndGroup ();\n    }\n}	0
7728789	7728730	How to set C# Property with Linq Statement?	public string UserName {\n    get {\n        return (from u in context.Users\n                where u.UserID==session["UserID"]\n                select u.UserName).SingleOrDefault(); \n    }\n}	0
19291446	19291317	How to make lambda do one db call instead of severals	var dates = messageList.Select(m => m.MessageDate).ToList();\nvar dayFlags = db.DayFlags.GroupBy(flag => flag.FlagDate)\n                          .Where(group => dates.Contains(group.Key))\n                          .Select(group => group.First());	0
33736784	33736675	Button image sides cropped	this.buttonOk.BackColor = System.Drawing.SystemColors.MenuHighlight;\n            this.buttonOk.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("buttonOk.BackgroundImage")));\n            this.buttonOk.BackgroundImageLayout = System.Windows.Forms.ImageLayout.Stretch;\n            this.buttonOk.DialogResult = System.Windows.Forms.DialogResult.Cancel;\n            this.buttonOk.Location = new System.Drawing.Point(475, 15);\n            this.buttonOk.Name = "buttonOk";\n            this.buttonOk.Size = new System.Drawing.Size(50, 50);\n            this.buttonOk.TabIndex = 11;\n            this.buttonOk.UseVisualStyleBackColor = false;\n            this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click);	0
25675731	25675007	Export XElement to Excel	using (var writer = new StreamWriter(@"C:\temp\yourfile.csv"))\n        {\n            string header = "DateModified,ModifiedBy,CustomerPricing,Id,Customer,Code";\n            writer.WriteLine(header);\n            foreach (var log in logs)\n            {\n                string line = "\"" + log.DateModified.ToShortDateString() + "\",\"" + log.ModifiedBy + "\",\"" +\n                              // you don't have a CustomerPricing element, as the whole object is CustomerPricing\n                              // add a "Price" element and sub out the element value below\n                              //log.ChangedData.Element("CustomerPricing").Value + "\",\"" +\n                              log.ChangedData.Element("Id").Value + "\",\"" +\n                              log.ChangedData.Element("Customer").Value + "\",\"" +\n                              log.ChangedData.Element("Code").Value + "\"";\n\n                writer.WriteLine(line);\n            }\n\n        }	0
30115185	30115109	Best way to get substrings of a longer string	string rawData = "Car: volvo Wheels: 4 doors: 5";\n        var words = Regex.Split(rawData, @"\w+:").Select(x => x.Trim()).Where(x => x.Length > 0).ToList();\n        var car = words[0];\n        var wheels = words[1];\n        var doors = words[2];	0
19514086	19513763	Interface with List of same interface	class Program\n{\n    static void Main(string[] args)\n    {\n        var holder = new Holder<IObject>();\n        holder.MyItem = new Object { List = new List<IObject>() };\n        holder.ChangeItemList(new Object { List = new List<IObject>() });\n    }\n}\n\npublic class Object : IObject\n{\n    public List<IObject> List { get; set; }\n}\n\npublic interface IObject\n{\n    List<IObject> List { get; set; }\n}\n\npublic class Holder<T> where T : IObject\n{\n    public T MyItem { get; set; }\n\n    public void ChangeItemList(T item)\n    {\n        MyItem.List = item.List;\n    }\n}	0
34486768	34486741	Get keys pressed while application not open?	[DllImport("user32.dll")]\nstatic extern IntPtr SetWindowsHookEx(int idHook, keyboardHookProc callback, IntPtr hInstance, uint threadId);	0
23255850	23255002	Cookies Response Issue With AutoPostBack	protected void cbPop_CheckedChanged(object sender, EventArgs e)\n{\n    Response.Cookies["UserPreferences"].Value = \n       Request.Cookies["UserPreferences"].Value + "1";\n    Label1.Text = Response.Cookies["UserPreferences"].Value.Length.ToString();\n    //                ^\n    //                |\n}\n\nprotected void cbDown_CheckedChanged(object sender, EventArgs e)\n{\n    Response.Cookies["UserPreferences"].Value = \n        Request.Cookies["UserPreferences"].Value + "2";\n    Label1.Text = Response.Cookies["UserPreferences"].Value.Length.ToString();\n    //                ^\n    //                |\n}	0
16805942	16801644	Testing Password format	public static class CryptoExtensions {\n\n    public static void ChangePasswordEx(this AsaMembershipProvider mp, string username, string oldPassword, string newPassword){\n        // validate format of the password\n        if (true /*validation code*/ )\n        {\n            throw new Exception("Invalid password format");\n        }\n\n        // rest of the code to encrypt and store the password\n        mp.ChangePassword(username, oldPassword, newPassword);\n    }\n\n}	0
23939860	23923632	Associate file types with my application C#	//HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\.avi\UserChoice -->"Progid" "Applications\YEPlayer.exe"\n        OpenMethod = Registry.CurrentUser.OpenSubKey(@"Software\Classes\Applications\", true);\n        OpenMethod.CreateSubKey(KeyName + @".exe\shell\open\command").SetValue("",'"'+OpenWith+'"'+ " "+ '"'+"%1"+'"');\n\n        FileExts = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\FileExts\", true);\n        foreach (string child in FileExts.OpenSubKey(Extension).GetSubKeyNames())\n        {\n            FileExts.OpenSubKey(Extension,true).DeleteSubKey(child);\n        }\n        FileExts.CreateSubKey(Extension + @"\UserChoice").SetValue("Progid", @"Applications\" + KeyName +".exe");\n    }	0
17978980	17978619	How can I put unescaped XML into the XmlText field for a class?	public class Material\n{\n    [XmlIgnore]\n    public string MaterialText { get; set; } \n\n    [XmlElement(ElementName = "mattext")]\n    public XmlElement MatText\n    {\n        get {\n            var doc = new XmlDocument();\n            doc.LoadXml(MaterialText);\n            return doc.DocumentElement;\n        }\n        set { /* implement in a similar way */ }\n   }	0
6415206	6415116	Adding more columns to a datatable in c#	string columnFourName = "Col4";\nstring columnFourName = "Col5";\nList<object> columnFourItems = new List<object>()\nList<object> columnFiveItems = new List<object>()\nSqlConnection oConn = new SqlConnection("SomeConnstring);\noConn.Open();\nSqlCommand oComm = new SqlCommand("SELECT * FROM Stuff", oConn);\nSqlDataAdapter sda = new SqlDataAdapter(oComm);\nDataTable dt = new DataTable();\nsda.Fill(dt);\ndt.Columns.Add(columnFourName, typeof(object));\ndt.Columns.Add(columnFiveName, typeof(object));\nfor (int row = 0; row < dt.Rows.Count; row++)\n{\n    dt.Rows[row][3] = columnFourItems[row];\n    dt.Rows[row][4] = columnFiveItems[row];\n}	0
32244770	32243811	Unity - change scene after specific time	using UnityEngine;\nusing System.Collections;\n\npublic class Test : MonoBehaviour\n{\n    bool loadingStarted = false;\n    float secondsLeft = 0;\n\n    void Start()\n    {\n        StartCoroutine(DelayLoadLevel(10));\n    }\n\n    IEnumerator DelayLoadLevel(float seconds)\n    {\n        secondsLeft = seconds;\n        loadingStarted = true;\n        do\n        {\n            yield return new WaitForSeconds(1);\n        } while (--secondsLeft > 0);\n\n        Application.LoadLevel("Level2");\n    }\n\n    void OnGUI()\n    {\n        if (loadingStarted)\n            GUI.Label(new Rect(0, 0, 100, 20), secondsLeft.ToString());\n    }\n}	0
24408740	16784798	How to Drag, Drop and Resize Label on a Panel at runtime? C#, winForms	private Point _Offset = Point.Empty;\n    private void ctrlToMove_MouseDown(object sender, MouseEventArgs e)\n    {\n        if (e.Button == MouseButtons.Left)\n        {\n            _Offset = new Point(e.X, e.Y);\n        }\n    }\n\n    private void ctrlToMove_MouseUp(object sender, MouseEventArgs e)\n    {\n        _Offset = Point.Empty;\n    }\n\n    private void ctrlToMove_MouseMove(object sender, MouseEventArgs e)\n    {\n        if (_Offset != Point.Empty)\n        {\n            Point newlocation = ctrlToMove.Location;\n            newlocation.X += e.X - _Offset.X;\n            newlocation.Y += e.Y - _Offset.Y;\n            ctrlToMove.Location = newlocation;\n        }\n    }	0
7826594	7826543	In ASP.NET MVC 3 with built-in user login using Forms, how can I retrieve a list of currently logged in users?	var onlineUsers = Membership.GetAllUsers()\n    .Cast<MembershipUser>().Where(u => u.IsOnline);	0
10295060	10294928	How values from SPListItem before and after Event?	if (properties.ListTitle == "ListName")\n    {\n         //AfterProperties gives new value and ListItem gives the previously stored\n         if(properties.AfterProperties["ColumnName"].ToString()!=properties.ListItem["ColumnName"].ToString())\n         //Your code Here\n    }	0
15024256	15023915	Select data to be shown in combobox or hide what I need	IList<MaterialType> materialTypes =  (from tom in context.MaterialTypes\n                                      where tom.IsActive == true\n                                      select tom).ToList(); //do you really need to split ID's from Names?\n\nmaterialTypes.Insert(0, new MaterialType { Name = "-- No Material --" }); //add to our list fake material\n\ncombobox.ValueMember = "ID";\ncombobox.DisplayMember = "Name";\ncombobox.DataSource = materialTypes;	0
24299059	24298935	How to bind gridview with some conditions in asp.net?	DataTable dtbind1 = objvehicleBAL.GetTaxdetails();\n DataTable dtbind2 = new DataTable();\n\n foreach (DataRow row in dtbind1.Rows)\n {\n     DateTime dt1 = DateTime.ParseExact(row["todate"].ToString(), "dd/MM/yyyy", null);\n     if (dt1 < ((DateTime.Now.AddDays(15))))\n          dtbind2.Rows.Add(row);\n     }\n }\n\n GVTax.DataSource = dtbind2;\n GVTax.DataBind();	0
12088418	12087367	get href value from html anchor tag C#	string ref= @"<a href=""http://www.google.com"">test</a>";\n var regex = new Regex("<a [^>]*href=(?:'(?<href>.*?)')|(?:\"(?<href>.*?)\")", RegexOptions.IgnoreCase);\n var urls = regex.Matches(ref).OfType<Match>().Select(m => m.Groups["href"].Value).SingleOrDefault();	0
11930763	11930673	 save information for user without authorization	FormsAuthentication.SetAuthCookie(Guid.NewGuid(), true)	0
13899072	13898949	Unit test assertion that is true in several cases	// Act phase: you get result somehow\nvar result = 42;\n\n// Assert phase\nresult.Should().BeOneOf(new [] { 1, 2 } ); \n// in this case you'll be following error:\n// Expected value to be one of {1, 41}, but found 42.	0
8941583	8941422	Faster replacement for Regex	Match()	0
10364393	10364233	get thumbnail from rss feed linq, xml	XDocument feedXML = XDocument.Load("http://feeds.bbci.co.uk/news/world/middle_east/rss.xml");\nXNamespace media = XNamespace.Get("http://search.yahoo.com/mrss/");\nvar feeds = from feed in feedXML.Descendants("item")\n                select new\n                {\n                    Title = feed.Element("title").Value,\n                    Link = feed.Element("link").Value,\n                    Description = feed.Element("description").Value,\n                    pubDate = feed.Element("pubDate").Value,\n                    guid = feed.Element("guid").Value,\n                    thumbnail = feed.Element(media+"thumbnail")!=null ? feed.Element(media+"thumbnail").Attribute("url").Value : ""\n                };	0
34473033	34456140	Unity3D - A generic way to compare one field's value to another field or value	public class FieldReference\n{\n    public GameObject gObject;\n    public string component;\n    public string fieldName;\n    public string value {\n        get {\n            return gObject.GetComponent (component).GetType ().GetField (fieldName).GetValue (gObject.GetComponent (component)).ToString ();\n        }\n    }\n}	0
4303662	4303605	C# Breaking larger method into two threads	public int LargeMethod()\n{\n    int result = 0;\n    Task<int> t1 = new Task<int>(SmallMethodA);\n    Task<int> t2 = new Task<int>(SmallMethodB);\n    t1.Start();\n    t2.Start();\n    result += t1.Result;\n    result += t2.Result;\n    return result;\n}	0
8035536	8035502	What is the best way to get a single value out of a dataset?	// setup sql command and sql connection etc first...\nint count = (int) cmd.ExecuteScalar();	0
21312361	21312166	How to read and compare data from an SQL Server Express database	...\nconnection.Open();\nvar name = command.ExecuteScaclar().ToString();\nconnection.Close();\n\nif (name != null) {\n  MessageBox.Show("This name already exists");\n  return;\n}	0
5593847	5593527	Configuring Sharepoint 2010 to send emails using C sharp with aspx	SPUtility.SendEmail(SPContext.Current.Web, false, false,\n                    "test@example.com", "E-mail title", "E-mail body");	0
14018487	14018333	C# Save reference to string variables in array	Dictionary<string, string>	0
11741228	11740229	c# unit-test with signed-assemblies	[assembly: InternalsVisibleTo("AssemblyName, PublicKey=xxx")]	0
21446305	21446288	Get page name from URI, substring between two characters	System.IO.Path.GetFileNameWithoutExtension(@"/Pages/Alarm/AlarmClockPage.xaml");	0
8605856	8605577	Linq expression in Razor view to access child property - how to use view model instead?	private CustomerOrderItem _HighestValueOrderItem = null;\npublic CustomerOrderItem HighestValueOrderItem { \nget{\n   if(this.CustomerOrderItems.Any() && _HighestValueOrderItem != null){\n        _HighestValueOrderItem =  this.CustomerOrderItems.OrderByDescending(i => i.SalesPrice).FirstOrDefault();\n        return  _HighestValueOrderItem;\n   } else {\n      return new CustomerOrderItem();\n   }\n}\n}	0
256273	256234	How do I get access to SOAP response	public class MyClientSOAPExtension : SoapExtension\n{\n\n     Stream oldStream;\n     Stream newStream;\n\n     // Save the Stream representing the SOAP request or SOAP response into\n     // a local memory buffer.\n     public override Stream ChainStream( Stream stream )\n     {\n            oldStream = stream;\n            newStream = new MemoryStream();\n            return newStream;\n     }\n\n    public override void ProcessMessage(SoapMessage message)\n    {\n       switch (message.Stage)\n        {\n            case SoapMessageStage.BeforeDeserialize:\n                // before the XML deserialized into object.\n                break;\n            case SoapMessageStage.AfterDeserialize:\n                break;        \n            case SoapMessageStage.BeforeSerialize:\n                break;\n            case SoapMessageStage.AfterSerialize:\n                break;            \n            default:\n                throw new Exception("Invalid stage...");\n        }       \n    }\n}	0
31614341	31613506	Non-ui blocking tasks with WPF/Caliburn	public ViewModel ViewModel\n{\n    get\n    {\n        return DataContext as ViewModel;\n    }\n}\n\npublic void OnLoaded()\n{\n    ViewModel.DoThatThing();\n}	0
18897004	16851994	DevExpress ASPxTreeList CommandColumn Buttons Size	...\n<dx:TreeListCommandColumn>\n   <CellStyle Font-Size="20px">\n   </CellStyle>\n</dx:TreeListCommandColumn>\n...	0
758134	758120	How do I dynamically create multiple controls in Silverlight?	Enumerable.Range(0, 10)\n          .Select(x => new FirstCircleControl())\n          .ToList()                        // Forces creation of controls.\n          .ForEach(x => Circles.Add(x));   // Adds them to the list.	0
19122330	19121956	How to authenticate user without login	var userId = "123";\n\nusing (UsersContext db = new UsersContext())\n{\n   UserProfile userProfile = db.UserProfiles.FirstOrDefault(u => u.UserId == userId);\n   FormsAuthentication.SetAuthCookie(userProfile.UserName, false);\n}	0
19704103	19702976	WinForms main window handle	protected override void OnHandleCreated(EventArgs e) {\n        base.OnHandleCreated(e);\n        SetWpfInteropParentHandle(this.Handle);\n    }	0
18864336	18864007	Reduce file size with DotNetZip	zip.CompressionLevel= Ionic.Zlib.CompressionLevel.BestCompression;	0
32115119	32112429	An expression of non-boolean type specified in a context where a condition is expected, near	SET @SQLScript = 'SELECT b.name\nFROM tblBrand b \nJOIN tblStore s ON b.PK_BrandID = s.FK_BrandID\nJOIN tblCustomReportTemp  CT on b.PK_BrandID = CT.BrandID\nWHERE b.Active =1 '\n\nif(@reportname is not null)\n        set @SQLScript = @SQLScript + ' AND CT.ReportName = ''' + @reportname + ''''\n\n    if(@username is not null)\n        set @SQLScript = @SQLScript + ' AND CT.UserName = ''' + @username + ''''	0
21271276	20107698	Windows phone 7 binding color to textbox	new SolidColorBrush(Color.FromArgb(255, 245, 171, 0));	0
715281	715090	SQL Reporting: Null Parameter	List<ReportParameter> myParams = new List<ReportParameter>();\n\nReportParameter p = new ReportParameter("Start_Date");\np.Values.Add(null);\nmyParams.Add(p);\n\n//myParams.Add(new ReportParameter("Start_Date")); \n// I even tried omiting this line.  \n//(This is the null parameter I wish to pass)\nmyParams.Add(new ReportParameter("End_Date", EndDate));\n\nReportViewer1.ServerReport.SetParameters(myParams);	0
7922113	7921773	direct file download instead of opening with a handler - file size showing issue	//context = HttpContext\ncontext.Response.Clear();\ncontext.Response.ContentType = varMimeType;\ncontext.Response.TransmitFile(filePath);\ncontext.Response.AddHeader("content-disposition", "attachment;filename=" + varFileName);\ncontext.Response.AddHeader("Content-Length", filePathFileInfo.Length);\ncontext.Response.Flush();\ncontext.Response.End();	0
20785413	20784924	How can I add a new line to a text document	string path = C:\...\text1.text\n List<string> lines = File.ReadAllLines(path);\n int i = 1;\n\n foreach (var line in lines)\n{\n   Console.WriteLine("{0}. {1}", i, line);\n   i++;\n }\n\n  Console.Write("Choose which line to edit: ");\n  int n = int.Parse(Console.ReadLine());\n  n--;\n\n Console.Write("{0}. ", n + 1);\n\nlines.Insert(n, Console.ReadLine());\n\nFile.WriteAllLines(path, lines.ToArray());	0
10675372	10675320	Get current IP from adapter name?	adapter.GetIPProperties().UnicastAddresses.Single(a => a.Address.AddressFamily == AddressFamily.InterNetwork).Address	0
4615177	4609012	How to deliberately crash a COM object	for(;;);	0
1253587	1172177	Evaluating SQL-query to LINQ-object - C#	IEnumerable<XElement> linq;\nlinq = (IEnumerable<XElement>)XElement.Parse(RawXmlData.ToString()).Elements();	0
13053929	13053892	Split a string and join it back together in a different order?	string modified = string.Format("{2}-{1}-{0}-{3}-{4}", tokens);	0
11065175	11035205	WPF - print during a loop	private void methodName()\n{\n    for (int i = 0; i < 2; i++)\n    {\n        updateTextBox(i.ToString());\n\n        this.canvas.UpdateLayout();\n\n        PrintDialog dialog = new PrintDialog();\n        dialog.PrintVisual(this.canvas, "ABC");\n\n        dialog.PrintQueue.Refresh();\n\n        while (dialog.PrintQueue.NumberOfJobs != 0)\n        {\n            bool isQueued = false;\n            foreach (var job in dialog.PrintQueue.GetPrintJobInfoCollection())\n            {\n                if (job.Name == "ABC")\n                    isQueued = true;\n            }\n\n            if (!isQueued)\n                break;\n\n            Thread.Sleep(500);\n            dialog.PrintQueue.Refresh();\n        }\n    }\n}\n\nprivate void updateTextBox(string text)\n{\n    txtTextBox.Text = text;\n}	0
29126126	29125600	How to replace names with hyperlinks	public string tags()\n{\n    string url = "http://www.testdomain.com/data.aspx";\n    string html = Story();\n    DataTable tags = LoadAllTags();\n\n    if (tags.Rows.Count > 0)\n    {\n        foreach(var row in tags.Rows)\n        {\n            foreach(var column in tags.Columns)\n            {\n                var tag = column.ToString();\n                var path = string.Format("{0}?SearchName={1}", url, HttpUtility.UrlEncode(tag);\n                var link = string.Format("<a href=\"{0}\">{1}</a>", path, tag);\n                html = html.Replace(tag, link);\n            }\n        }\n    }\n    return html;\n}	0
10755998	10755854	linq-to-sql null or default	var result = new MyModel {\n                          Total = <yourDataSource>\n                            .Count(x.TheDate >= StartDate && x.TheDate <= EndDate)\n                          };	0
24488505	24486337	Datagridview with query in C#	private void Form56_Load(object sender, EventArgs e)\n        {\n\n\n            try\n            {\n                MySqlConnection cnn = new MySqlConnection("MY CONNECTION");\n\n                cnn.Open();\n                // - DEBUG \n                // MessageBox.Show("Connection successful!"); \n                MySqlDataAdapter MyDA = new MySqlDataAdapter();\n                MyDA.SelectCommand = new MySqlCommand("MY QUERY", cnn);\n                DataTable table = new DataTable();\n                MyDA.Fill(table);\n\n                BindingSource bSource = new BindingSource();\n                bSource.DataSource = table;\n\n                dataGridView1.DataSource = bSource;\n\n            }\n            catch (MySql.Data.MySqlClient.MySqlException ex)\n            {\n                MessageBox.Show(ex.Message);\n                Close();\n            }\n\n        }	0
4507912	4507878	Disable client certificate trust in C#	using System;\n\nusing System.Security.Cryptography.X509Certificates;\n\n\npublic class X509\n{\n\n    public static void Main()\n    {\n\n        // The path to the certificate.\n        string Certificate = "Certificate.cer";\n\n        // Load the certificate into an X509Certificate object.\n        X509Certificate cert = new X509Certificate(Certificate);\n\n        // Get the value.\n        string resultsTrue = cert.ToString(true);\n\n        // Display the value to the console.\n        Console.WriteLine(resultsTrue);\n\n        // Get the value.\n        string resultsFalse = cert.ToString(false);\n\n        // Display the value to the console.\n        Console.WriteLine(resultsFalse);\n\n    }\n\n}	0
15114712	15114352	how to access listview of other form	// Call:\nForm2 test = new Form2(this);\n\n//Constructor Form2:\npublic Form2 (Form1 FormToAccess)\n\n//Access:\nFormToAccess.listBox1.... = ... ;	0
26395062	26395038	How to work with the contents of my array?	int[][] stores = {new int [] {2000,4000,3000,1500,4000},\n              new int [] {6000,7000,8000},\n              new int [] {9000,10000}};\n\nConsole.WriteLine("Row 1 average: {0}", stores[0].Average());\nConsole.WriteLine("Row 2 average: {0}", stores[1].Average());\nConsole.WriteLine("Row 3 average: {0}", stores[2].Average());	0
12377798	12365849	BLToolkit using a MySQL connection	class BlDb : DbManager\n{\n    public BlDb()\n        : base( new BLToolkit.Data.DataProvider.MySqlDataProvider(), "Server=myServerAddress;Database=myDataBase;Uid=myUsername;Pwd=myPassword" )\n    {           \n    }\n    public Table<Car> Car { get { return GetTable<Car>(); } }\n    public Table<Make> Make { get { return GetTable<Make>(); } }\n}	0
19951030	19950599	How to convert listbox DataContext to string in windows phone 7	void Appointments_SearchCompleted(object sender, AppointmentsSearchEventArgs e)\n  {\n     try\n     {\n        AppointmentResultsData.DataContext = e.Results;\n        MessageBox.Show(e.Results.ElementAt<Appointment>(0).Subject.ToString());\n     }\n     catch (System.Exception) { }\n  }	0
34034194	34033787	Creating a ListViewItem from a Dataset row where a subitem has multiple elements	foreach (DataRow dr in ds.Tables["movie"].Rows)\n{\n    item = new ListViewItem(new string[]\n    {\n        dr["title"].ToString(),\n        dr["year"].ToString(),\n        dr["rating"].ToString(),\n        string.Join(", ", dr.GetChildRows("movie_actor").Select(a => a[0])),\n        dr["director"].ToString(),\n        string.Join(", ", dr.GetChildRows("movie_genre").Select(a => a[0])),\n        dr["length"].ToString(),\n    });\n\n    listView1.Items.Add(item);\n}	0
27637578	27623596	Importing a CSV file to textbox but not formatting properly	hex.Split(",\r\n".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);	0
18571519	18570752	Selecting Node from xml file using xpath	XmlDocument xmlDoc = new XmlDocument();\nxmlDoc.Load(filepath);\nXmlElement root = xmlDoc.DocumentElement;\nXmlNode node = root.SelectSingleNode("SurveySetting");\nif (node != null && node.Attributes.Count > 0 && node.Attributes["IsServeyOn"] != null && !string.IsNullOrEmpty(node.Attributes["IsServeyOn"].Value))\n  {\n        RadiobuttonSurverysetting.SelectedValue = node.Attributes["IsServeyOn"].Value;\n  }	0
4472480	4472369	Returning a Distinct IQueryable with LINQ?	public static IQueryable GetActiveEmployees_Grid(string Period)\n    {\n        DataContext Data = new DataContext();\n        var Employees = (from c in DataSystem_Records\n                         where c.Period == Period\n                         orderby c.DataSystem_Employees.LName\n                         select c).GroupBy(g=>g.DataSystem_Employees.AccID).Select(x=>x.FirstOrDefault());\n\n        return Employees;\n    }	0
23185249	23183550	NewtonSoft Json serializer performance	public static string Serialise(YourObject data)\n{\nStringBuilder sb = new StringBuilder();\nStringWriter sw = new StringWriter(sb);\n\nusing (JsonWriter writer = new JsonTextWriter(sw))\n{\n    writer.WriteStartObject();\n\n    writer.WritePropertyName("propertyName1");\n\n    if (data.Property1 == null)\n    {\n        writer.WriteNull();\n    }\n    else\n    {\n        writer.WriteValue(data.Property1);\n    }\n\n    writer.WritePropertyName("propertyName2");\n\n    writer.WriteStartArray();\n\n    foreach (var something in data.CollectionProperty)\n    {\n        writer.WriteStartObject();\n\n        writer.WritePropertyName("p1");\n        writer.WriteValue(something.prop1);\n\n        writer.WritePropertyName("p2");\n        writer.WriteValue(something.prop2);\n\n        writer.WritePropertyName("p3");\n        writer.WriteValue(something.prop3);\n\n        writer.WriteEndObject();\n    }\n\n    writer.WriteEndArray();\n\n    writer.WriteEndObject();\n}\n\nreturn sb.ToString();\n}	0
31491595	31489783	Setting visibility and activity of a component in a callback	public void ProcessCompleteCallback()\n{\n    MessageBox.Show("Process completed.");\n    Application.Current.Dispatcher.Invoke(() => \n    {\n        GenerateOutputButton.IsEnabled = true;\n        LoadingGifImage.Visibility = Visibility.Hidden;\n        CommandManager.InvalidateRequerySuggested();\n    });\n}	0
22742181	22741684	How to find cells having same values in DataGridView?	Dictionary<string, List<int>> data = new Dictionary<string,List<int>>();\n\n    foreach (DataGridViewRow row in dataGridView1.Rows)\n    {\n        string name = row.Cells[1].ToString();\n        int ID =  Convert.ToInt32(row.Cells[0]);\n        if (data.ContainsKey(name)) data[name].Add(ID);\n        else data.Add(name, new List<int>(new int[] { ID }));\n    }\n\n    foreach (string name in data.Keys)\n        if (data[name].Count > 1 ) \n        {\n            Console.Write(name);\n            foreach (int ID in data[name]) Console.Write(ID.ToString("##### "));\n            Console.WriteLine();\n        }	0
8067792	8067167	What is the best way to validate a email domain?	nslookup -type=mx <domain.name>	0
2130203	2130123	Secure a registry key via ACL to remove all access to non administrators	AddAccessRule()	0
8869827	8869812	a faster way to download multiple files	public static void Main(string[] args)\n    {\n        var urls = new List<string>();\n        Parallel.ForEach(\n            urls, \n            new ParallelOptions{MaxDegreeOfParallelism = 10},\n            DownloadFile);\n    }\n\n    public static void DownloadFile(string url)\n    {\n        using(var sr = new StreamReader(HttpWebRequest.Create(url).GetResponse().GetResponseStream()))\n        using(var sw = new StreamWriter(url.Substring(url.LastIndexOf('/'))))\n        {\n            sw.Write(sr.ReadToEnd());\n        }\n    }	0
16695420	16694950	Convert code to C# from VB script	Process proc = new Process();\n\nproc.StartInfo.FileName = @"C:\Program Files\Ipswitch\WS_FTP Professional\ftpscrpt.com";\nproc.StartInfo.Arguments = @"-f P:\share\getfiles.scp";\nproc.StartInfo.RedirectStandardOutput = true;\nproc.StartInfo.RedirectStandardError = true;\nproc.StartInfo.UseShellExecute = false;\n// start the process\nproc.Start();\n// wait for it to finish\nproc.WaitForExit(5000);     \n// get results\nstring output = proc.StandardOutput.ReadToEnd();\nstring error = proc.StandardError.ReadToEnd();	0
21399701	21384061	Animating height of custom made control in C#	Storyboard.SetTargetProperty(animation, new PropertyPath(FrameworkElement.HeightProperty));	0
23710024	23709969	Button tapped event not firing in universal app	ScrollViewer Grid.Row="1"..	0
9641708	9641574	How do I resize a BitmapImage to 50x50 on Windows Phone 7?	WriteableBitmap wBitmap = new WriteableBitmap(yourBitmapImage);\n\nMemoryStream ms = new MemoryStream();\n\nwBitmap.SaveJpeg(ms, 50, 50, 0, 100);	0
21093122	21088074	Lambda expression with .Where clause using Contains	private List<UserInformationProxy> GetContactsFromGuidList(List<Guid> contactList)\n{\n    var qe = new QueryExpression(Contact.EntityLogicalName);\n    qe.ColumnSet = new ColumnSet("fullname", "contactid")\n    qe.Criteria.AddCondition("contactid", ConditionOperator.In, list.Cast<Object>().ToArray());\n    qe.Distinct = true;\n\n    var results = service.RetrieveMultiple(qe).Entities.Select (e => e.ToEntity<Contact>()).\n        Select(x => new UserInformationProxy()\n        {\n            FullName = x.FullName,\n            Id = x.ContactId\n        });\n\n    return results;\n}	0
7110631	7110300	uploading images in winforms appliaction	if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)\n{\n    string selectedFile = openFileDialog1.FileName;\n}	0
9040411	8818224	How to change listview header's forecolor? C# windows form application	namespace WindowsFormsApplication1\n{\n    public partial class Form1 : Form\n    {\n        public Form1()\n        {\n            InitializeComponent();\n\n            this.SetLastColumnWidth();\n\n            this.theListView.Layout += delegate\n            {\n                this.SetLastColumnWidth();\n            };\n        }\n\n        private void SetLastColumnWidth()\n        {\n            // Force the last ListView column width to occupy all the\n            // available space.\n            this.theListView.Columns[ this.theListView.Columns.Count - 1 ].Width = -2;\n        }\n\n        private void listView1_DrawColumnHeader( object sender, DrawListViewColumnHeaderEventArgs e )\n        {\n            // Fill header background with solid yello color.\n            e.Graphics.FillRectangle( Brushes.Yellow, e.Bounds );\n            // Let ListView draw everything else.\n            e.DrawText();\n        }\n    }\n}	0
10674789	10665778	Encrypting a private key with BouncyCastle	"PBEwithSHA-1and3-keyDESEDE-CBC"	0
20342052	20318043	Get stream from path wp8	var store =     \n    System.IO.IsolatedStorage.IsolatedStorageFile.GetUserStoreForApplication();\nvar newPath = "MyFileName.png";\n\nif (store.FileExists(newPath)) store.DeleteFile(newPath);\n\nvar stream = store.CreateFile(newPath);\n\nBitmapImage i = new BitmapImage();\ni.SetSource(photoResult.ChosenPhoto);\nWriteableBitmap imageToSave = new WriteableBitmap(i);\nimageToSave.SaveJpeg(stream, 173, 173, 0, 100);\n\nstream.Flush();\nstream.Close();	0
6616666	6616589	How can I retrieve multiple selected listbox items and cast them to objects?	ProcessSelection(lstbDataFields.SelectedItems.Cast<ClassDataField>())	0
337008	336988	XML Serialization and Schema without xsd.exe	System.Xml.Serialization.XmlSchemaExporter	0
25211225	25211179	Code executes all of onStartup() without waiting for user input in view	protected override void OnStartup(StartupEventArgs e)\n{\n    base.OnStartup(e);\n\n    MainWindow window = new MainWindow();\n\n    Window1 test = new Window1();\n    test.ShowDialog();\n\n    if (test.InvalidLicense)\n    {\n        Shutdown();\n        return;\n    }\n\n    window.Show();\n}	0
25744647	25744603	Type conversion from T to string and from string to T, where T is known to be string	value = (T)(object)(value.ToString().Substring(0,length));	0
7387108	7387085	How to Read an Entire file to a String using C#	string contents = File.ReadAllText(@"C:\temp\test.txt");	0
2706987	2697351	C# Client to Consume Google App Engine RESTful Webservice (rpc XML)	// send request\nHttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://localhost:8080/xmlrpc/");\nrequest.Method = "POST";\nrequest.ContentType = "text/xml; encoding=utf-8";\n\nstring content = "<?xml version='1.0'?><methodCall><methodName>app.getName</methodName><params></params></methodCall>"; \nbyte[] contentBytes = System.Text.UTF8Encoding.UTF8.GetBytes(content);                      \nrequest.ContentLength = contentBytes.Length;\nusing (Stream stream = request.GetRequestStream())\n{\n    stream.Write(contentBytes, 0, contentBytes.Length); \n}\n\n// get response\nWebResponse response = request.GetResponse();\nXmlDocument xmlDoc = new XmlDocument();\nusing (Stream responseStream = response.GetResponseStream())\n{\n    xmlDoc.Load(responseStream);\n    Console.WriteLine(xmlDoc.OuterXml);\n}	0
14839439	14839223	set property values from outside an object	internal interface IServiceAInternal\n{\n    ServiceResponse ProcessFromServiceB(ServiceRequest request);\n}\n\npublic class ServiceA : IServiceA, IServiceAInternal\n{\n    public ServiceResponse Process(ServiceRequest request)\n    {\n        return ProcessCore(request, false);\n    }\n\n    ServiceResponse IServiceAInternal.ProcessFromServiceB(ServiceRequest request)\n    {\n        return ProcessCore(request, true);\n    }\n\n    private ServiceResponse ProcessCore(ServiceRequest request, bool calledFromServiceB)\n    {\n        ...\n    }\n}\n\npublic class ServiceB : IServiceB\n{\n    private readonly IServiceAInternal _serviceA;\n\n    public ServiceB()\n    {\n        _serviceA = Container.Get<IServiceAInternal>();\n    }\n\n    public ServiceResponse ReProcess(ServiceRequest request)\n    {\n        return _serviceA.ProcessFromServiceB(request);\n    }\n}	0
10462461	10462445	HTML Selector Library	HtmlDocument doc = new HtmlDocument();\ndoc.Load("file.htm");\nforeach(HtmlNode link in doc.DocumentElement.SelectNodes("//a[@href"])\n{\n   HtmlAttribute att = link["href"];\n   att.Value = FixLink(att);\n}\ndoc.Save("file.htm");	0
27817599	27815594	C# / C++ application crashes when run from Windows, but not from Visual Studio	_NO_DEBUG_HEAP = 1	0
10003009	10002811	C# Insert ArrayList in DataRow	ArrayList array = new ArrayList();\n\n        String[] arrayB = new String[array.Count];\n        for (int i = 0; i < array.Count; i++)\n        {\n            arrayB[i] = array[i].ToString();\n        }\n\n        valuesdata.Rows.Add(arrayB);	0
27103718	27103447	Parsing CSV data	// Add Microsoft.VisualBasic.dll to References.\nusing Microsoft.VisualBasic.FileIO; \n\n// input is your original line from csv.\n\n// Remove starting and ending quotes.\ninput = input.Remove(0, 1);\ninput = input.Remove(input.Length - 1);\n\n// Replace double quotes with single quotes.\ninput = input.Replace("\"\"", "\"");\n\nstring[] result;\nusing (var csvParser = new TextFieldParser(new StringReader(input)))\n{\n    csvParser.Delimiters = new string[] { "," };\n    result = csvParser.ReadFields();\n}	0
30893945	30888764	Web Api 2 + EF6 - Building a DTO	class FooRepository\n{\n   public async Task<List<FooDTO>> FindAsync()\n   {\n       using(var context = new DbContext())\n       {\n           return await context.Foos\n               .Select(m => new FooDTO\n               {\n                   Id = m.Id,\n                   ...\n               })\n               .ToListAsync();\n       } \n   }\n}	0
17095062	17094898	Need help writing a LINQ statement	foreach(var noxRecord in CurrentPermit.PermitDetails.Where(a => a.PermitConstituentTypeId == 2)\n{\n    var ppmAt15PercentOxygen = noxRecord.PpmAt15PercentOxygen;\n}	0
6494292	6494272	enum in constructor - how to?	public enum Color { Black, Yellow, Blue, Green };\n\nclass Circle\n{\n    public const double PI = 3.14;\n\n    private Color _color;\n    int radius;\n\n    public Circle(int radius, Color color)\n    {\n        this.radius = radius;\n        this._color = color;\n    }\n}	0
28929253	28929089	How to add a value to a RadioButtonList	protected void Page_Load(object sender, EventArgs e)\n{   \n    if (!Page.IsPostBack)\n    {\n        //Question\n        lblQuestion1.Text = "Which of the following is not a country in Europe?";\n\n        //Answers\n        lstAns1.Items.Add(new ListItem("Enland", "0"));\n        lstAns1.Items.Add(new ListItem("Germany", "0"));\n        lstAns1.Items.Add(new ListItem("France", "0"));\n        lstAns1.Items.Add(new ListItem("Canada", "1"));\n    }\n}	0
9161720	9161260	C# Winforms DatagridView - setting different Color of button for different row	r.Cells(9).Style.BackColor = Drawing.Color.Red	0
3368405	3368391	In a generic list, is there a way to copy one property to another in a declarative /LINQ manner?	// Return true so All will go through the whole list.\nbooks.All(book => { book.TitleTarget = book.TitleSource; return true; });	0
25444972	25444924	Surrounding a lambda expression parameter with parentheses	var singleString = someStrings.Aggregate((current, next) => current + Environment.NewLine + next);	0
22687175	22686997	Split a string containing digits	var str = "abc kskd 8.900 prew";\nvar result = Regex.Split(str, @"\W(\d.*)").Where(x => x!="").ToArray();	0
13675762	13675743	C#, using all files with the same extension in a folder	foreach (FileInfo fi in new DirectoryInfo(@"C:\documents").GetFiles().Where(x => x.Extension.ToLower() == ".doc")) {\n    Console.WriteLine(fi.Name);\n}	0
21633674	21629915	Windows Service: Define asynchnous method that runs after startup - SignalR Client	protected override async void OnStart(string[] args)\n        {\n            eventLog1.WriteEntry("In OnStart");\n            try\n            {\n                var hubConnection = new HubConnection("http://localhost/AlphaFrontEndService/signalr", useDefaultUrl: false);\n                IHubProxy alphaProxy = hubConnection.CreateHubProxy("AlphaHub");\n\n                await hubConnection.Start();\n                // Invoke method on hub\n                await alphaProxy.Invoke("Hello", "Message from Service");\n\n            }\n            catch (Exception ex)\n            {\n                eventLog1.WriteEntry(ex.Message);\n            }\n        }	0
33429665	33429612	How to Create a folder into My Documents or another Path?	Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "MyDirectory"));	0
6123166	6123090	How to copy from list to stack without using loop	var myStack = new Stack<MyObjectType>(myList);	0
5577703	5565635	StackOverflowException trying to return a Linq query result as a List through a WCF Service	Model.Entities entities = new Model.Entities();\n\n        public ServicePeople()\n        {\n            entities.ContextOptions.ProxyCreationEnabled = false;\n            entities.ContextOptions.LazyLoadingEnabled = false;\n        }	0
4619337	4619268	How to do this with Databinding	this.comboBox1.ItemSource = names.Select(o=>o.SaveName)	0
4174500	4174491	Get Color from int	private static Color getcolor(int grayScale)\n{\n   return Color.FromArgb(grayScale, grayScale, grayScale);\n}	0
1648056	1276975	How do I change image upload path *dynamically* in FCKeditor	string Userfolder = Session["UserInfo"].ToString();\n// URL path to user files.\nUserFilesPath = "~/Upload/" + Userfolder;	0
31989685	31988942	models for input and models for views, do you separate? c#	public class PersonModel\n{\n    string firstName;\n    string Surname;\n    DateTime DateOfBirth\n}\npublic class PersonDisplayViewModel\n{\n    PersonModel Model;\n    string FullName\n    {\n        get{return Model.firstname + " " + Model.Surname;}\n    }\n    int Age\n    {\n        get{return (DateTime.Today() - Model.DateOfBirth).TotalYears;}\n    }\n}\npublic class PersonEditViewModel\n{\n    PersonModel Model;\n    string FirstName {\n        get{return Model.FirstName;}\n        set{Model.FirstName = value;}\n    }\n    string Surname{\n        get{return Model.Surname;}\n        set{Model.Surname= value;}\n    }\n    DateTime DateOfBirth{\n        get{return Model.DateOfBirth;}\n        set{Model.Surname= DateOfBirth;}\n    }\n\n}	0
4043040	4040735	Change non static object from static Context	public static readonly DependencyProperty IsInReadModeProperty = DependencyProperty.Register(\n    "IsInReadMode",\n    typeof(bool),\n    typeof(RegCardSearchForm),\n    new UIPropertyMetadata(false, ReadModeChanged));\n\nprivate static void ReadModeChanged(DependencyObject dObj, DependencyPropertyChangedEventArgs e)\n{\n    RegCardSearchForm form = dObj as RegCardSearchForm;\n    if (form != null)\n        form.ReadModeChanged((bool)e.OldValue, (bool)e.NewValue);\n}\n\nprotected virtual void ReadModeChanged(bool oldValue, bool newValue)\n{\n    // TODO: Add your instance logic.\n}	0
22129585	22129163	Opposite to Hold Event in Windows Phone 8 C#	private void MyImage_ManipulationCompleted(object sender, ManipulationCompletedEventArgs e)\n{\n    if(isSoundPlaying) stopSound();\n}	0
27547320	27547259	How to select value in DatagridviewComboboxColumn Cell	public Form1()\n    {\n        InitializeComponent();\n\n        DataGridViewComboBoxColumn cmbcolumn = new DataGridViewComboBoxColumn();\n        dataGridView2.EditingControlShowing += new DataGridViewEditingControlShowingEventHandler(dataGridView2_EditingControlShowing);\n\n\n    }\n\n    private void dataGridView2_EditingControlShowing(object sender, DataGridViewEditingControlShowingEventArgs e)\n    {\n        ComboBox combo = e.Control as ComboBox;\n        if (combo != null)\n        {\n            combo.SelectedIndexChanged -= new EventHandler(ComboBox_SelectedIndexChanged);\n            combo.SelectedIndexChanged += new EventHandler(ComboBox_SelectedIndexChanged);\n        }\n    }\n\n    private void ComboBox_SelectedIndexChanged(object sender, EventArgs e)\n    {\n        ComboBox cb = (ComboBox)sender;\n        string item = cb.Text;\n        if (item == "Add")\n        {\n            Categorie cat = new Categorie();\n            cat.Show();\n\n        }\n    }	0
33467743	33467698	How to get listview values in other page.xaml	public hinoDetail()\n{\n    this.InitializeComponent();\n\n}\n\nprotected override void OnNavigatedTo(NavigationEventArgs e)\n{\n    hinos result = (e.Parameter as List<hinos>).FirstOrDefault(); //gets the first one only\n   textBlock.Text = result.nameHino\n\n}\n\npublic async void mostraHino()\n{\n\n}	0
11074080	10759632	Lambda expressions for refactor-safe ArgumentException	Expression<Func<T, object>>	0
1287999	1180364	How do you get file details in a SharePoint ItemEventReciever in the ItemAdding Event?	private HttpContext context;\n\npublic MyItemEventReceiver() {\n    context = HttpContext.Current;\n}\n\npublic override void ItemAdding(SPItemEventProperties properties) {\n    HttpFileCollection collection = context.Request.Files;\n    foreach (String name in collection.Keys) {\n    if (collection[name].ContentLength > 0) {\n    // Do what you need with collection[name].InputStream\n    }\n    }\n}	0
29984085	29984011	How to retrieve Ajax header in this asp.NET web api method?	var headers = Request.Headers.GetValues("AjaxHeader");\nvar ajaxHeader = headers.FirstOrDefault();	0
28834804	28834688	Stop Visual Studio 2013 from automatically removing extra spaces in assignments	Tools->Options->Text Editor->C#->Formatting->Spacing	0
28387500	28387338	convert php preg_replace to C#	var result = Regex.Replace("david", "[b-df-hj-np-tv-z]", "$0o$0" );	0
593239	593227	Retrieve description and category of node with LINQ	from c in context\nwhere c.Attribute("category") == "category name"\nselect new\n{\n  Description = c.Attribute("desc"),\n  Category =  c.Attribute("category")\n}	0
16360011	16359896	Custom helper loading an image and that would work as a link	public static MvcHtmlString Image(this HtmlHelper _helper, string _url, string _altText, object _htmlAttributes)\n{\n    TagBuilder builder = new TagBuilder("image");\n    TagBuilder anchorabBuilder = new TagBuilder("a"); \n\n    var path = _url.Split('?');\n\n    string pathExtra = "";\n\n    if (path.Length > 1)\n    {\n        pathExtra += "?" + path[1];\n    }\n\n    builder.Attributes.Add("src", VirtualPathUtility.ToAbsolute(path[0]) + pathExtra);\n    builder.Attributes.Add("alt", _altText);\n    builder.MergeAttributes(new RouteValueDictionary(_htmlAttributes));\n    anchorabBuilder.InnerHtml = builder.ToString(TagRenderMode.SelfClosing);\n    return MvcHtmlString.Create(anchorabBuilder.ToString(TagRenderMode.Normal));\n}	0
4620107	2065435	Is it possible to set the Windows language bar to english or back to the default from a c# application	Process[] apps=Process.GetProcesses();\nforeach (Process p in apps){\nif (p.MainWindowHandle.ToInt32()>0)\n                    {\n                        NativeWin32.SetForegroundWindow(p.MainWindowHandle.ToInt32());\n\n                        System.Windows.Forms.SendKeys.SendWait("^+(2)"); //send control shift 2 to switch the language bar back to english.\n                        p.Dispose();\n                    }\n                }	0
16744373	16744316	how to set the location of lable in c# , i want to use some point in my project to set the location	label1.Location = p2; // your point	0
18178198	18177931	How to pass arguments to thread in C#	void SetThread()\n    {\n        for (int i = 0; i < _intArrayLength; i++)\n        {\n           int currentValue = i;\n            Console.Write(string.Format("SetThread->i: {0}\r\n", i));\n            _th[i] = new Thread(() => RunThread(currentValue));\n            _th[i].Start();\n        }\n    }	0
6451355	4246235	Set VS DefaultLocation based on build configuration	setup.exe TARGETDIR="C:\App"	0
11920073	11919856	Matching similar words using RegEx	string s= "This island is a colony; however,it is autonomous and receives no orders from the mother country, autonomy, N.";;\nstring pattern="autonomous";\nRegex r=new Regex(@"\b(?!"+pattern+")"+pattern.Substring(0,pattern.Length/2)+@".*?\b");\nr.Replace(s,".");	0
30104742	30104587	Saving date with datetimepicker through dropdown menu or manualy selecting a date	public MyClass()\n{\n\n   YourDateTimePickerId.Value = DateTime.Now.AddDays(1);\n   MessageBox.Show(dateTimePicker1.Value.ToString());\n}	0
614690	614640	How do I add a namespace while doing XmlSerialization with an XmlWriter?	[XmlElement(\nElementName = "Members",\nNamespace = "http://www.cpandl.com")]\npublic Employee[] Employees;	0
21054938	21054264	regex matching Title-case or ALLCAPS with unicode chars	^([\p{Lu}\p{Lt}]\p{L}+\s*){2,5}	0
27235686	27093065	DateTimeOffset Same Day comparison	public static bool SameDate(DateTimeOffset first, DateTimeOffset second)\n{\n    bool returnValue = false;\n    DateTime firstAdjusted = first.ToUniversalTime().Date;\n    DateTime secondAdjusted = second.ToUniversalTime().Date;\n\n    // calculate the total diference between the dates   \n    int diff = first.Date.CompareTo(firstAdjusted) - second.Date.CompareTo(secondAdjusted);\n    // the firstAdjusted date is corected for the difference in BOTH dates.\n    firstAdjusted = firstAdjusted.AddDays(diff);\n\n    if (DateTime.Compare(firstAdjusted, secondAdjusted) == 0)\n        returnValue = true;\n\n    return returnValue;\n}	0
12854738	12854686	Regular expression to replace with empty string	string result = Regex.Replace(input,@"^[^A-Z]*","");	0
30000779	29063771	How to refresh a WinRTXamlToolkit Chart to display changed data	((AreaSeries)CHART_Overview.Series[0]).ItemsSource = null;\n((AreaSeries)CHART_Overview.Series[0]).ItemsSource = _lstLogOvw;	0
8155662	8155425	Fastest search of a collection of objects by specifying a property of an object in .NET	public class Holder\n{\n    public Action OnPropChange;\n\n    int _prop;\n    public int Prop\n    {\n        get\n        {\n            return _prop;\n        }\n        set\n        {\n            _prop = value;\n            OnPropChange();\n        }\n    }\n}\n\npublic class SortedListThing : List<Holder>\n{\n    public void Add(Holder h)\n    {\n        BinarySortedInsert(h);\n        h.OnPropChange = () => { this.Remove(h); base.Add(h); };\n    }\n\n    private void BinarySortedInsert(Holder h)\n    {\n        //do stuff\n    }\n\n    public void Remove(Holder h)\n    {\n        h.OnPropChange = null;\n        base.Remove(h);\n    }\n}	0
6939139	6938744	ASP.NET MVC3 C# - when user clicks button, change record in DB from 1 to 2 and viceversa	public ActionResult DetailsChanged(DetailsRepository detailsRepository, Details detailsModel)\n{\n  if(!ModelState.Valid)\n{\n   ViewData["Error"] = "Error";\n   return View();\n}\n\nDetails newDetails = detailsRepository.FirstOrDefault(x => x.ID == detailsModel.Id);\nif(newDetails != null)\n{\n   if(newDetails.Id == 1)\n   {\n      newDetails.Id = 2;\n   } else {\n      newDetails.Id = 2;\n   }\n   detailsRepository.SaveChanges();\n   return View();\n }\n}	0
15259205	15259151	Using a SQL Server Stored Procedure in Visual Studio	using (var conn = new SqlConnection(connectionString))\n{\n    using (var comm = conn.CreateCommand())\n    {\n        conn.Open();\n        comm.CommandText = "SOME SQL HERE";\n\n        // command type, parameters, etc.\n\n        //pick one of the following\n        comm.ExecuteNonQuery();\n        int value = (int)comm.ExecuteScalar();\n        SqlDataReader reader = comm.ExecuteReader();\n\n    }\n}	0
24517969	24488430	SyndicationFeed - item summary (RSS description) - extract only text from it	// Get rid of the tags\ndescription = Regex.Replace(description, @"<.+?>", String.Empty);\n\n// Then decode the HTML entities\ndescription = WebUtility.HtmlDecode(description);	0
23579559	22042095	ServiceStack: The maximum array length quota (16384) has been exceeded while reading XML data	DataContractSerializer.Instance = new DataContractSerializer(new XmlDictionaryReaderQuotas\n{  \n    MaxStringContentLength = /* new value */; \n};	0
7816288	7816260	Multiple "Insert Into" operation under same event	private void addMainBookInfos() \n{ \n    using (SqlConnection con = new SqlConnection(Conn.Activated))\n    using (SqlCommand com = new SqlCommand("AddBook", con))\n    {\n        com.CommandType = CommandType.StoredProcedure; \n        com.Parameters.AddWithValue("@BookISBN", txtISBN.Text);             \n\n        com.ExecuteNonQuery()\n\n        // close can be omitted since you are already using the 'using' statement which automatically closes the connection\n        con.Close(); \n    }\n}	0
14532888	14530886	Cannot create a semaphore as standard user on Windows 7	const string NAME = "Global\\MySemaphore";	0
33757069	33756962	How to control checkbox Situation in List View asp.net C#	foreach (ListViewItem row in ListView2.Items)\n    {            \n        CheckBox cb = (CheckBox)row.FindControl("CheckBox1");\n            if( cb != null)\n            {\n                if (cb.Checked == true)\n                {\n                       //Some Stuf..\n                }\n            }\n    }	0
11080188	11080007	Setting entity key in GET action	//\n    // POST: /Blog/Comment/5\n\n    [HttpPost]\n    public ActionResult Comment(int id, Comment comment)\n    {\n        if (ModelState.IsValid)\n        {\n            db.Comments.AddObject(comment);\n            comment.PostReference.EntityKey = new EntityKey("BlogEntities.Posts", "id", id);\n            db.SaveChanges();\n            return RedirectToAction("Index");\n        }\n\n        return View();\n    }	0
27126138	27080343	Parsing a web page and extracting data	HtmlDocument doc = new HtmlDocument();\n    doc.Load("file.html");\n    string phone_number = doc.DocumentElement.SelectNodes("//td[contains(text(), 'Phone')]//following-sibling::td[1]"]).InnerText	0
17814556	17814408	generating integer random numbers in c#	List<int> used = new List<int>();\nRandom random = new Random();\n\nforeach(thing you want to do)\n{\n    int current = random.Next(1000, 9999);\n\n    while(used.Contains(current))\n        current = random.Next(1000, 9999);\n\n    //do something\n\n    used.Add(current);\n}	0
29262346	25987960	Extract text from SmartArt in Presentation OpenXml	static void Main(string[] args)\n{\n    using (var p = PresentationDocument.Open(@"SmartArt.pptx", true))\n    {\n        foreach (var slide in p.PresentationPart.GetPartsOfType<SlidePart>().Where(sp => IsVisible(sp)))\n        {\n            foreach(var diagramPart in slide.DiagramDataParts)\n            {\n                foreach(var text in diagramPart.RootElement.Descendants<Run>().Select(d => d.Text.Text))\n                {\n                    Console.WriteLine(text);\n                }\n            }\n        }\n    }\n\n    Console.ReadLine();\n}\n\nprivate static bool IsVisible(SlidePart s)\n{\n    return (s.Slide != null) &&\n      ((s.Slide.Show == null) || (s.Slide.Show.HasValue &&\n      s.Slide.Show.Value));\n}	0
1790864	1790810	Most suitable .net Timer for a scheduler	LinkedList<T>	0
6358982	6358843	How to get the current active view in a region using PRISM?	var singleView = regionManager.Regions["MyRegion"].ActiveViews.FirstOrDefault();	0
19591489	19591324	How to select an item from a listbox in windows phone?	private void DetailButton_Click_1(object sender, RoutedEventArgs e)\n{\n    var clickedUIElement =  sender as Button;\n    if (null == clickedUIElement) { Return; }\n    Display selectedItemData = clickedUIElement.DataContext as Display;\n    if(null != selectedItemData)\n    {\n        NavigationService.Navigate("/page3.xaml", selectedItemData);\n    }\n}	0
33121240	33107859	Updating an entity with required properties in Entity Framework	using (var context = GetContext())\n{\n  var userEntity = new UserEntity() { ID = userUpdate.ID };\n  context.Users.Attach(userEntity);\n  context.Entry(userEntity).CurrentValues.SetValues(userUpdate);\n\n  // Disable entity validation\n  context.Configuration.ValidateOnSaveEnabled = false;\n\n  context.SaveChanges();\n}	0
17792323	17791746	How to authenticate a xml in c#?	WebRequest request = WebRequest.Create(url);\nNetworkCredential credential = new NetworkCredential(username, password);\n\nrequest.Credentials = credential;\nrequest.PreAuthenticate = true;\n\nWebResponse response = request.GetResponse();\nStream Answer = response.GetResponseStream();\n\nStreamReader _Answer = new StreamReader(Answer); \nstring content = _Answer.ReadToEnd(); //the string of the whole xml\nresponse.Close();	0
30240412	30237868	Read, write, from and to a file using C#	static void Main(string[] args)\n{\n    String Readfiles = File.ReadAllText(@"C:\Users\ken4ward\Desktop\Tidy\WriteLines.txt");\n    Int32 myInt = Int32.Parse(Readfiles);\n\n    //Declare array outside the loop\n    String[] start = new String[myInt];\n\n    for (int i = 0; i < myInt; ++i)\n    {\n        //Populate the array with the value (add one so it starts with 1 instead of 0)\n        start[i] = (i + 1).ToString();\n\n        Console.WriteLine(i);\n        Console.ReadLine();  \n    }\n\n    //Write to the file once the array is populated\n    File.WriteAllLines(@"C:\Users\ken4ward\Desktop\Tidy\writing.txt", start);\n}	0
33801710	33801565	Entity framework filter lambda navigation properties	var resultObjectList = _context.\n                   Parents.\n                   Where(p => p.DeletedDate == null).\n                   OrderBy(p => p.Name).\n                   Select(p => new\n                             {\n                                 ParentItem = p,\n                                 ChildItems = p.Children.Where(c => c.Name=="SampleName")\n                             }).ToList();	0
3366283	3366092	Set a default value to a property and make it serializable	[DefaultValue("SomeValue")]\npublic string Prop { get; set; }	0
11275996	11275948	Struggling to convert SQL to LINQ	from od in db.OrderDetails\n    join o in db.Orders on od.OrderID equals o.OrderID\n    join p in db.Products on od.ProductID equals p.ProductID\nwhere o.CustomerID == "ALFKI"\ngroup od by new { p.ProductID, p.ProductName } into g1\nselect new { \n    ProductName = g1.Key.ProductName, \n    Total = g1.Sum(od => od.Quantity) }	0
18651904	18651736	Pass Column Name as parameter	CREATE PROCEDURE dbo.StoredProcedure2\n\n    @columnName varchar(50),\n    @batchmId  int\nAS\n\n    DECLARE @SQL1 AS VARCHAR(MAX)\n    DECLARE @SQL2 AS VARCHAR(MAX)\n\n    SET @SQL1 = 'select ' + @columnName + ' from Batch_Master'\n\n    SET @SQL1 = 'select ' + @columnName + '\n         from GTIN_Master inner join Batch_Master\n         on GTIN_Master.GTIN = Batch_Master.GTIN\n         where Batch_M_id =' + CONVERT(VARCHAR,@batchmId)\n\n    IF EXISTS(SELECT * FROM sys.columns WHERE Name = @columnName and Object_ID = Object_ID(N'Batch_Master'))\n        BEGIN    \n            EXEC (@SQL1)\n        END\n    ELSE\n        BEGIN\n            EXEC (@SQL2)\n        END	0
14717919	14717670	Webservice expecting JSON, sending multipart-form data	[OperationContract]\n    SuccessUpload uploadDoc2(Stream data);	0
21161840	21161746	How to resolve Code Analysis - CA1720 for GUID datatype	[SuppressMessage("Microsoft.Naming", "CA1720:IdentifiersShouldNotContainTypeNames")]	0
1402365	1402356	Getting information from my loaded DataTable	Tabla.Rows[0]["mycolumnName"]	0
23860558	23860512	How do I redirect a checkbox to another page in my app if checked Xamarin Android C#?	private void MainPage_Load(object sender, EventArgs e)\n{\n    checkBox1.CheckedChanged += checkBox1_CheckedChanged;\n}\nprivate void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n    if (checkBox1.Checked)\n    {\n        // your code to go to the other page.\n    }\n}	0
9891705	9891409	Efficient data pattern to store three related items for easy access	class BookmarkObj { /* similar to steven's */ }\nclass BookmarkStore {\n Dictionary<int, BookmarkObj> byId;\n Dictionary<DateTime, BookmarkObj> byStartDate;\n Dictionary<DateTime, BookmarkObj> byEndDate;\n\n /* Boring init code */\n\n public void Insert(BookmarkObj obj) {\n  byId[obj.Id] = obj;\n  byStartDate[obj.Start] = obj;\n  byEndDate[obj.End] = obj;\n }\n\n public BookmarkObj GetById(int id) {\n  return byId[obj.Id];\n }\n\n /* And so on */	0
15980520	15980329	How do I have my getter return data from attribute/metadata?	MemberInfo property = typeof(YourClass).GetProperty("PropertyName");   \nvar attribute = property.GetCustomAttributes(typeof(MyCustomAttribute), true)\n      .Cast<MyCustomAttribute>.Single();\nstring displayName = attribute.DisplayName;	0
10253036	10252675	Create Json dynamically in c#	[TestFixture]\npublic class DynamicJson\n{\n    [Test]\n    public void Test()\n    {\n        dynamic flexible = new ExpandoObject();\n        flexible.Int = 3;\n        flexible.String = "hi";\n\n        var dictionary = (IDictionary<string, object>)flexible;\n        dictionary.Add("Bool", false);\n\n        var serialized = JsonConvert.SerializeObject(dictionary); // {"Int":3,"String":"hi","Bool":false}\n    }\n}	0
32024970	32024626	Add Columns to DataGridView	private void dataGridView2_CellClick(object sender, DataGridViewCellEventArgs e)\n{\n    /* Place indexes here, there is no need to initialize   *\n     * so many integers inside loop if they're not changing */\n    int indexOfYourColumn = 9, index2 = 0;\n\n    var restaurantList = new List<Restaurant>();\n    foreach (DataGridViewCell cell in dataGridView2.SelectedCells)\n    {\n        foreach (DataGridViewRow row in dataGridView1.Rows)\n        {\n            if (cell.Value.ToString() == row.Cells[indexOfYourColumn].Value.ToString())\n            {\n                restaurantList.Add(new Restaurant()\n                {\n                    Data  = row.Cells[indexOfYourColumn].Value.ToString(),\n                    Data2 = row.Cells[index2].Value.ToString()\n                });\n            }\n        }\n    }\n\n    dataGridView3.DataSource = restaurantList;\n}	0
28292042	28291591	How to access a nested JSON string?	string json_string = "{\"1\":{\"oid\":\"2892\",\"order\":\"SD1427999310502\"},\n                      \"all\":1,\"time\":\"2015-02-02 10:37:55\"}";\n\nJObject outer_object = JObject.Parse(json_string);\nJObject inner_object = (JObject)outer_object["1"];\nstring oid_value = inner_object["oid"].ToString();\nstring order_value = inner_object["order"].ToString();	0
31430209	31429920	Prevent users from tampering with the view's increment code	[WebMethod (EnableSession=true)]	0
14595329	14595271	Designing a dynamic panel	private void button1_Click(object sender, EventArgs e)\n    {\n        tabControl1.SelectedIndex = 0;\n        tabControl1.TabPages[0].Text = "First";\n    }\n\n    private void button2_Click(object sender, EventArgs e)\n    {\n        tabControl1.SelectedIndex = 1;\n    }\n\n    private void button3_Click(object sender, EventArgs e)\n    {\n        tabControl1.SelectedIndex = 2;\n    }	0
10673360	10673158	Get twitter public timeline, json+C#, no 3rd party libraries	using (WebClient webClient = new WebClient())\n{\n    string url = "http://api.twitter.com/1/statuses/public_timeline.json";\n    dynamic json = JsonConvert.DeserializeObject(webClient.DownloadString(url));\n\n    foreach (var item in json)\n    {\n        Console.WriteLine("{0} {1}", item.user.id, item.user.screen_name);\n    }\n}	0
9403553	9403507	Query Dates From SQLServer in C#?	using (HumanResourcesDB db = newHumanResourcesDB(ConfigurationManager\n            .ConnectionStrings["HumanResourcesDB"].ConnectionString))\n{\n    List<Employee> record = (from tab in db.Employees\n     where tab.Birthday >= DateTime.Today\n     && tab.Birthday < DateTime.Today.AddDays(31)\n     select tab).ToList();\n\n    this.grdBirthdays.DataSource = record;\n\n    this.grdBirthdays.DataBind();\n}	0
8713376	8713218	One DataSource for multiple controls	lbxXunit.DataSource = units;\nlbxYunit.DataSource = units.ToList();	0
9479378	9477132	how to false visibility of Data Grid View snippet?	DatagGridView.Columns[*Column No/Name*].Visible = false;	0
23642589	23642543	How to filter a combobox using another combobox in C#?	ComboBox.SelectedIndexChanged Event	0
9644041	9606575	Can I use reactive extensions to queue calls to a windows service?	var eventLoop = new EventLoopScheduler();\n\nIObservable<Unit> QueueAnItem(string input) \n{\n    return Observable.Start(() => CallGhostScriptAndWaitForItToFinish(input), eventLoop);\n}\n\nQueueAnItem("Foo").Subscribe(\n    x => Console.WriteLine("It Finished!"), \n    ex => Console.WriteLine("Something Bad Happened: {0}", ex.ToString());	0
16737244	16735923	Serial port fragmented data	SetText(serialPort1.ReadExisting());	0
30243755	30239586	How to detect if column in SELECT can be null?	var joins = querySpecification.FromClause.TableReferences.OfType<QualifiedJoin>();	0
13231799	12964437	List in list (Model) Factory	var list = _dictImportantInformation.GetList().ToList().Select(\n            x => new DictionaryNewInfoListModel\n                     {\n                         Id = x.Id,\n                         Description = x.Description,\n                         IsActiveYN = x.IsActive,\n                         DeestynationName = x.DictImportantInformationXDestination.Select(n => new DictionaryNewInfoSupportList \n                         { Id = n.Destination.Id, Name = n.Destination.Description }).ToList()\n                     }\n\n            ).ToList();	0
32236521	32219777	How to perform amazon cloud search with .net code?	// Configure the Client that you'll use to make search requests\nstring queryUrl = @"http://search-<domainname>-xxxxxxxxxxxxxxxxxxxxxxxxxx.us-east-1.cloudsearch.amazonaws.com";\nAmazonCloudSearchDomainClient searchClient = new AmazonCloudSearchDomainClient(queryUrl);\n\n// Configure a search request with your query\nSearchRequest searchRequest = new SearchRequest();\nsearchRequest.Query = "potato";\n// TODO Set your other params like parser, suggester, etc\n\n// Submit your request via the client and get back a response containing search results\nSearchResponse searchResponse = searchClient.Search(searchRequest);	0
3477683	3477598	How to set Color of control without using the Enumeration?	Color slateBlue = Color.FromName("SlateBlue");	0
27523274	27523224	Add variable number of XElements	XElement apps = \nnew XElement("Applications",\n    new XElement("Application",\n        new XAttribute("Name", name),\n        new XAttribute("CFBundleIdentifier", bundle),\n        (from icon in icons\n        select new XElement("Icon", icon,\n                new XAttribute("Size", iconsize)))\n        )\n    );	0
19876607	19872820	How To Get Sql Database Backup File's Data and Log File Paths Using SMO in C#	restore filelistonly from disk='path_to_your_backup'	0
30551226	30550834	Load a C-Dll in C# with struct array as parameter	struct Test\n{\n    public int test1;\n    public int test2;\n}\n\n[DllImport("mydll", CallingConvention = Cdecl)]\npublic static extern void FillStruct( Test[] stTest, int size);\n\n[...]\nvar test = new Test[n];\nFillStruct(test, test.Length);	0
18547530	18547491	How do I cancel third party task?	Thread.Abort	0
18437583	18429420	DataGridView doesnt show scrollbar	try\n{\n    dataGridView.ScrollBars = ScrollBars.Both;\n\n    dConn.Open();\n    dAdapter4.Fill(ds4,"activities");\n    dConn.Close();    \n    dataGridView.DataSource = ds4.Tables[0].DefaultView;\n}	0
3107491	3107474	How to add Process Instruction to an XML file in C#	using System;\nusing System.Xml.Linq;\n\npublic class Test\n{\n    static void Main()\n    {\n        XDocument doc = XDocument.Load("test.xml");\n        var proc = new XProcessingInstruction\n            ("xml-stylesheet", "type=\"text/xsl\" href=\"Sample.xsl\"");\n        doc.Root.AddBeforeSelf(proc);\n        doc.Save("test2.xml");\n    }\n}	0
11085124	11084506	How to Convert Wpf BitmapSource to byte[] in C#	JpegBitmapEncoder encoder = new JpegBitmapEncoder();\n        encoder.Frames.Add(BitmapFrame.Create(bitmapSource));\n        encoder.QualityLevel = 100;          \n        byte[] bit = new byte[0];\n        using (MemoryStream stream = new MemoryStream())\n        {               \n            encoder.Frames.Add(BitmapFrame.Create(bitmapSource));\n            encoder.Save(stream);\n            bit = stream.ToArray(); \n            stream.Close();               \n        }	0
18080720	18080682	C# Best practice - Counting how many times each date occurs	dates.GroupBy(d => d).ToDictionary(g => g.Key, g => g.Count());	0
21965339	21965306	How to create a ?0000001? type number format in C#?	String.Format(CultureInfo.InvariantCulture, "{0:0000000}", number);	0
10603857	10603608	Webdriver "sendkeys" method doesn't enter password correctly	WebElement userNameField = driver.findElement(By.id("userNameTextBoxId"));\nWebElement passwordField = driver.findElement(By.id("passwordTextBoxId"));\nuserNameField.sendKeys("myusername");\npasswordField.sendKeys("mypassword");	0
4073492	4073440	Specifying multiple interfaces for a parameter	public void Foo<T>(T myParam)\n    where T : IObject, ITreeNode<IObject>\n{\n    // whatever\n}	0
17486097	17485548	Search Particular Word in PDF using Itextsharp	public  List<int> ReadPdfFile(string fileName, String searthText)\n            {\n                List<int> pages = new List<int>();\n                if (File.Exists(fileName))\n                {\n                    PdfReader pdfReader = new PdfReader(fileName);\n                    for (int page = 1; page <= pdfReader.NumberOfPages; page++)\n                    {\n                        ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();\n\n                        string currentPageText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);\n                        if (currentPageText.Contains(searthText))\n                        {\n                            pages.Add(page);\n                        }\n                    }\n                    pdfReader.Close();\n                }\n                return pages;\n            }	0
13817446	13817326	How to remove all digits after . value except two digits c#	string str = "123.00000000";\ntextBox1.Text = str.Substring(0,str.IndexOf(".")+3);	0
32272497	32259651	Specifying action in OperationContract results in no action generated in WSDL	[ServiceContract(Namespace = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03")]\n    public interface ITfsNotificationService\n    {\n        [OperationContract(Action = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03/Notify", Name = "Notify", ReplyAction = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03/ResponstToNotify")]\n        [XmlSerializerFormat(Style = OperationFormatStyle.Document)]\n        void Notify(string eventXml, string tfsIdentityXml, SubscriptionInfo SubscriptionInfo);\n    }\n\n    [ServiceBehavior(Namespace = "http://schemas.microsoft.com/TeamFoundation/2005/06/Services/Notification/03")]\n    public class Service1 : ITfsNotificationService\n    {\n        public void Notify(string eventXml, string tfsIdentityXml, SubscriptionInfo SubscriptionInfo)\n        {\n            throw new NotImplementedException();\n        }\n    }	0
9958353	9957525	Add a doctype to HTML via HTML Agility pack	HtmlDocument htmlDoc = new HtmlDocument();\n\nhtmlDoc.Load("withoutdoctype.html");\n\nHtmlCommentNode hcn = htmlDoc.CreateComment("<!DOCTYPE html>");\n\nHtmlNode htmlNode = htmlDoc.DocumentNode.SelectSingleNode("/html");\nhtmlDoc.DocumentNode.InsertBefore(hcn, htmlNode);\n\nhtmlDoc.Save("withdoctype.html");	0
16609516	16608266	Linq query to sum values from tables	from i in Invoices\nselect new\n{\n    InvoiceID = i.InvoiceId, \n    CustomerName = i.CustomerName,\n    SubPrice = InvoiceItems.Where(it => it.InvoiceID = i.InvoiceID).Select(it => it.Quantity*it.UnitPrice).Sum(),\n    SumPayments = PaymentInvoice.Where(pi => pi.InvoiceId = i.InvoiceId).Select(pi => pi.AmountAllocated).Sum()\n}	0
8862198	8861029	Passing Bitmap from C# to C++ Unmanaged code	static System::Drawing::Point FindImage(IntPtr source, IntPtr target)\n{\n    POINT retval = ImgFuncs::MyImgFuncs::FindImage((HBITMAP)(void*)source, (HBITMAP)(void*)target);\n    return System::Drawing::Point(retval.X, retval.Y);\n}	0
2381206	2381180	Building an object with a [] interface ( not from ILIst) in c#	public decimal this[int index] {\n    get { return data[index]; }\n    set { data[index] = value; }\n}	0
20899873	20899838	How to get last column name from a datatable	int count= mynew.Columns.Count;\nvar lastColumn = mynew.Columns[count - 1];\nstring columnname= lastColumn.ColumnName;	0
31024389	31023285	Search on array of multiple type objects	var data = from s in abc\n                          from i in s.Items\n                          select\n                              new\n                                  {\n                                      objType = i.GetType() == typeof(OR)                                             \n                                            ? ((OR)i).name : i.GetType() == typeof(DT)                                            \n                                            ? ((DT)i).name : string.Empty,\n                                      objAbc = s\n                                  };\n\nIEnumerable<abc> data = journey.Where(x => x.objType.Contains("myname")).Select(y => y.objAbc).ToList();	0
14375252	14374348	Refresh button - Refreshing data grid view after inserting, deleting, updating	DataTable dt = new DataTable();\n\nBindingSource bs = new BindingSource();\n\nbs.DataSource = dt;\n\ndataGridView1.DataSource= bs;	0
29892594	29891215	Access a parent window control(e.g a Label) inside Child page	Page page = new Page(this);  \nFramme.Content = page;	0
21752875	21752856	Attempting to order a list using IOrderedEnumerable in C#	List<string[]> users = new List<string[]>() ;	0
842897	842887	How to add list in ListBox?	double[] X = { ... };\ndouble[] Y = { ... };\nstring[] Risk = { ... };\n\nfor (int i = 0; i > X.Length; i++)\n{\n    TrainigSet tr = new TrainigSet(); // create a new TrainingSet\n    ...\n    listtraining.Add(tr);\n}	0
10531346	10531230	Search in List of List in C#	var Result = AList.Select(p => new\n        {\n            BList = p.BList,\n            indexes = p.BList.Select((q, i) => new\n            {\n                index = i,\n                isMatch = q.Word == "Word"\n            }\n            )\n            .Where(q => q.isMatch)\n            .Select(q=>q.index)\n        });	0
21159859	21159790	How do I check in SQLite whether a database exists C#	if(File.Exists("database.db"))	0
12752299	12752052	How to detect the state of a toggle button on a ribbon?	public void ToggleButtonOnAction(IRibbonControl control, bool pressed)\n{\n  MessageBox.Show("ToggleButton was switched " + pressed ? "on" : "off");\n}	0
9485798	9485766	How do I add leading zeroes to String.Format parameters?	string textTransDate = DateTime.Now.ToString("yyyy-MM-dd HH:mm");	0
7416977	7416922	Javascript to validate start date and end date in asp.net	if (startDate!= '' && EndDate!='') {  \n    var stdate = Date.parse(startDate);   \n    var enddate = Date.parse(EndDate);  \n    if (stdate > enddate) {   \n        alert('Start date cannot be greater than end date');   \n        return false;   \n    }   \n    else\n    {   \n        return true;   \n    }   \n}	0
5159079	5159055	How do I send e-mail using .NET 4 if smtp server requires authorization?	smtpServerInstance.Credentials = new NetworkCredential("user", "password"); \nsmtpServerInstance.Send(mail);	0
33128958	33128855	Get single value list of Company Codes for Combobox	foreach (var cc in qry.Distinct().ToList())	0
19450225	19450147	Lambda, get properties from nested list	var result = dbContext.UserRoles\n                   .Where(ur => ur.Customer.CustomerId == customer.CustomerId)\n                   .Select(ur => ur.UserProfile);	0
576878	576861	Drawing a line with a gradient color	protected override void OnPaint(PaintEventArgs e)\n{\n    base.OnPaint(e);\n\n    Graphics graphicsObject = e.Graphics;\n\n    using (Brush aGradientBrush = new LinearGradientBrush(new Point(0, 0), new Point(50, 0), Color.Blue, Color.Red))\n    {\n        using (Pen aGradientPen = new Pen(aGradientBrush))\n        {\n            graphicsObject.DrawLine(aGradientPen, new Point(0, 10), new Point(100, 10));\n        }\n    }\n}	0
6604746	6507774	StyleCop Custom Rules: Method Parameters and Variables	private bool VisitExpression(Expression expression, Expression parentExpression, Statement parentStatement, CsElement parentElement, object context)\n{\n    if (expression.ExpressionType == ExpressionType.VariableDeclarator)\n    {\n        VariableDeclaratorExpression declaratorExpression = (VariableDeclaratorExpression)expression;\n        if (declaratorExpression.Initializer == null)\n        {\n            this.AddViolation(parentElement, expression.LineNumber, "YourRule", declaratorExpression.Identifier.Text);\n        }\n    }\n\n    return true;\n}	0
15207655	15207275	Convert Image into Byte[]	Bitmap bmp = new Bitmap("c:\\fakePhoto.jpg");\nRectangle rect = new Rectangle(0, 0, bmp.Width, bmp.Height);\nBitmapData bmpData =\n   bmp.LockBits(rect, ImageLockMode.ReadWrite, bmp.PixelFormat);\n\nint bytes  = Math.Abs(bmpData.Stride) * bmp.Height;\nbyte[] rgbValues = new byte[bytes];\n\n// Copy the RGB values into the array.\nMarshal.Copy(bmpData.Scan0, rgbValues, 0, bytes);	0
12500088	12499965	Convert from query to method	var washingtonCustomers = customers.Where(c => c.Field<string>("Region") == "WA");\nvar recentOrders = orders.Where(o => (DateTime)o["OrderDate"] >= cutoffDate);\n\nvar query = washingtonCustomers.Join(recentOrders, \n                 c => c.Field<string>("CustomerID"),\n                 o => o.Field<string>("CustomerID"),\n                 (c, o) => new { \n                     CustomerID = c.Field<string>("CustomerID"), \n                     OrderID = o.Field<int>("OrderID") \n                 });	0
7573198	7572997	Read Excel data from C#	Range headers = mySheet.UsedRange.Rows(1);	0
1904276	1903425	C#: Open a browser and POST to a url from a windows desktop app	static void Main()\n{\n    Settings s = Settings.Default;\n    Process.Start(s.URL1);\n    Thread.Sleep(s.Delay1);\n    SendKeys.SendWait("%D");\n    Thread.Sleep(100);\n    SendKeys.SendWait(EncodeForSendKey(s.URL2));\n    SendKeys.SendWait("{ENTER}");\n}\n\npublic static string EncodeForSendKey(string value)\n{\n    StringBuilder sb = new StringBuilder(value);\n    sb.Replace("{", "{{}");\n    sb.Replace("}", "{}}");\n    sb.Replace("{{{}}", "{{}");\n    sb.Replace("[", "{[}");\n    sb.Replace("]", "{]}");\n    sb.Replace("(", "{(}");\n    sb.Replace(")", "{)}");\n    sb.Replace("+", "{+}");\n    sb.Replace("^", "{^}");\n    sb.Replace("%", "{%}");\n    sb.Replace("~", "{~}");\n    return sb.ToString();\n}	0
32560210	32559810	How I can copy data from one file in another one	var link = File.ReadLines(path + "\\text.txt").ToArray();\n        var sb = new StringBuilder();\n        foreach (var txt in link)\n        {\n            if (txt.Contains("Output="))\n            {\n                var outputPath = txt.Split('=')[1];\n                sb.AppendLine(string.Format("outlog = {0}", outputPath));\n\n            }\n            else if (txt.Contains("Licfile="))\n            {\n                var LicFilePath = txt.Split('=')[1];\n                sb.AppendLine(string.Format("license_path = {0}", LicFilePath));\n            }\n        }\n        File.WriteAllText(path + "\\text2.txt",sb.ToString());	0
23941444	23940989	Working with elements inside a control that is bound to a collection	private void Button_PreviewMouseRightButtonUp(object sender, MouseButtonEventArgs e)\n{\n    DockPanel dockPanel = (DockPanel)((Button)sender).Content;\n    TextBlock text = (TextBlock)LogicalTreeHelper.FindLogicalNode(dockPanel, "secondTextBlock");\n    if (text != null)\n    {\n        text.Visibility = Visibility.Visible;\n    }\n}	0
1521858	1521816	Winforms: One COM object needs an STAThread, the other needs an MTAThread. How can I use them?	ThreadStart threadEntryPoint = ...;\n\nvar thread = new Thread(threadEntryPoint);\nthread.ApartmentState = ApartmentState.MTA;  // set this before you call Start()!\nthread.Start();	0
14061978	14061472	Get all registered implementations of an interface in Autofac	var types = scope.ComponentRegistry.Registrations\n    .SelectMany(r => r.Services.OfType<IServiceWithType>(), (r, s) => new { r, s })\n    .Where(rs => rs.s.ServiceType.Implements<T>())\n    .Select(rs => rs.r.Activator.LimitType);	0
1646070	1644914	Reconciling two collections of objects	var originalPersons = m_originalList.ToList();\nm_originalList.Clear();\nforeach (var modifiedPerson in m_modifiedList)\n{\n    var originalPerson = originalPersons.FirstOrDefault(c => c.ID == modifiedPerson.ID);\n    if (originalPerson == null)\n        m_originalList.Add(modifiedPerson);\n    else\n    {\n        m_originalList.Add(originalPerson);\n        originalPerson.Document = modifiedPerson.Document;\n        originalPerson.Name = modifiedPerson.Name;\n        ...\n    }\n}	0
9149964	9149944	How to get the index of int array when using linq query	Quantities = numbers.Select((s, index) => new SelectListItem \n{ \n    Value = index.ToString(), \n    Text = s.ToString()\n);	0
13230606	13230583	Get the Path from a filename	Path.GetFullPath(fileName);	0
18765583	18752097	Visual Studio 2012 Deploying WPF via ClickOnce missing Files	ReceiptTemplates/templates.xml	0
10999000	10998455	Verifying a delegate was called with Moq	bool isDelegateCalled = false;\nvar a = new A(a => { isDelegateCalled = true});\n\n//do something\nAssert.True(isDelegateCalled);	0
33936763	33936716	Split a string with slash	string myString = "/1//2//56//21/";\n int[] arrayInt = Regex.Split(myString, "/+").Where(s => !String.IsNullOrWhiteSpace(s)).Select(Int32.Parse).ToArray();	0
1151640	1151610	Synchronising databases SQL Server via C#	using System;\nusing Microsoft.SqlServer.Dts.Runtime;\n\nnamespace RunFromClientAppCS\n{\n  class Program\n  {\n    static void Main(string[] args)\n    {\n      string pkgLocation;\n      Package pkg;\n      Application app;\n      DTSExecResult pkgResults;\n\n      pkgLocation =\n        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +\n        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";\n      app = new Application();\n      pkg = app.LoadPackage(pkgLocation, null);\n      pkgResults = pkg.Execute();\n\n      Console.WriteLine(pkgResults.ToString());\n      Console.ReadKey();\n    }\n  }\n}	0
25291424	25275343	How do I crop an ImageSurface in Cairo?	ImageSurface OutputImage = new ImageSurface (Format.Rgb24, (int)RectangleToCropTo.Width, (int)RectangleToCropTo.Height);\nusing (Cairo.Context cr = new Cairo.Context(OutputImage)) {\n    cr.SetSource (originalImage, -RectangleToCropTo.X, -RectangleToCropTo.Y);\n    cr.Paint ();\n}	0
9071933	9071581	How to read TIFF header File c#?	using System;\nusing System.Linq;\nusing System.IO;\n\nnamespace FileToHex\n{\n    class Program\n    {\n        static void Main(string[] args)\n        {\n            //read only 4 bytes from the file\n\n            const int HEADER_SIZE = 4;\n\n            byte[] bytesFile = new byte[HEADER_SIZE];\n\n            using (FileStream fs = File.OpenRead(@"C:\temp\FileToHex\ex.tiff"))\n            {\n                fs.Read(bytesFile, 0, HEADER_SIZE);\n                fs.Close();\n            }\n\n            string hex = BitConverter.ToString(bytesFile);\n\n            string[] header = hex.Split(new Char[] { '-' }).ToArray();\n\n            Console.WriteLine(System.String.Join("", header));\n\n            Console.ReadLine();\n\n        }\n    }\n}	0
4712901	4712830	Expression tree - join 2 expressions with and	public Expression<Func<TEntity, bool>> And(Expression<Func<TEntity, bool>> ex1, \n                                           Expression<Func<TEntity, bool>> ex2)\n{\n  var x = Expression.Parameter(typeof(TEntity));\n  return Expression.Lambda<Func<TEntity,bool>>(\n    Expression.And(\n      Expression.Invoke(ex1, x),\n      Expression.Invoke(ex2, x)), x); \n}	0
15550191	15549854	How to tell if event comes from user input in C#?	bool ignoreEvents = false;\n        public Form1()\n        {\n            InitializeComponent();\n        }\n\n        private void checkBox1_CheckedChanged(object sender, EventArgs e)\n        {\n            ignoreEvents = true;\n            checkBox2.Checked = checkBox1.Checked ;\n            checkBox3.Checked = checkBox1.Checked;\n            ignoreEvents = false;\n        }\n\n        private void checkBox2_CheckedChanged(object sender, EventArgs e)\n        {\n            if (ignoreEvents) return;\n            MessageBox.Show("Changed in 2");\n        }\n\n        private void checkBox3_CheckedChanged(object sender, EventArgs e)\n        {\n            if (ignoreEvents) return;\n            MessageBox.Show("Changed in 3");\n        }	0
23167320	23165608	Parsing JSON with shortened keys in C#	[DataMember(Name = "em")]\n    public string Email { get; set; }	0
5006822	5006595	How do my users keep their sqlCE database in .NET application up-to-date?	void AddQuestion(Question question);\nQuestion[] NewQuestions(DateTime fromDate);	0
6698361	6698298	how to assign a datacolumn value to a variable and use this variable in different method	public class Test\n{\n     private int ColValue {get;set;} //This is a property\n\n     button_click()\n     {\n          ColValue = Convert.ToInt(dataset.tables["ABC"].rows[0]["col name"].ToString()) ;\n     }\n\n     button_click2()\n     {\n         int y = ColValue ;\n     }\n}	0
539304	539198	Dynamic Grid In Silverlight 2 using C#	public void BuildGrid()\n{\n    LayoutRoot.ShowGridLines = true;\n    int rowIndex = 0;\n    foreach (string s in _names)\n    {\n        LayoutRoot.RowDefinitions.Add(new RowDefinition());\n        var btn = new Button()\n        LayoutRoot.Children.Add(btn);\n        Grid.SetRow(btn, rowIndex);\n        rowIndex += 1;\n    }\n}	0
30172196	30172103	How to debug .NET console application from Visual Studio 2013	System.Diagnostics.Debugger.Break();	0
1223503	1223490	Indexer as part of the interface in C#	public interface IYourList<T>\n    {\n        T this[int index] { get; set; }\n    }	0
5494916	5494897	How does one dynamically add new bindings using Ninject's DI during runtime?	void OnApplicationStart()\n{\n    StaticKernelContainer.Kernel = new StandardKernel(new YourInjectionModule());\n}\n\nvoid AfterMEFHasDoneWhatItNeedsToDo()\n{\n    // (You may need to use Rebind at this point)\n    StaticKernelContainer.Kernel.Bind<ICarLogger>().To(importer.CarType);\n}	0
9402167	9402135	An issue with 32 bit * 32 bit data in C#	System.Int32 x, y;\nSystem.Int64 z;\n\nSystem.Random rand = new System.Random(DateTime.Now.Millisecond);\nfor (int i = 0; i < 6; i++)\n{\n    x = rand.Next(int.MinValue, int.MaxValue);\n    y = rand.Next(int.MinValue, int.MaxValue);\n    z = ((Int64)x * y); //by casting x, we "promote" the entire expression to 64-bit.\n    Console.WriteLine("{0} * {1} = {2}", x, y, z);\n}	0
3340039	3336167	How do I make mutually exclusive columns in a WPF Data Grid?	public const string YearOneByIndexPropertyName = "YearOneByIndex";\npublic int YearOneByIndex\n{\n    get\n    {\n        return _yearOneByIndex;\n    }\n\n    set\n    {\n        if (_yearOneByIndex  == value)\n        {\n            return;\n        }\n\n        _yearOneByIndex = value;\n        _yearOneByPercentage = 0\n\n        RaisePropertyChanged(YearOneByIndexPropertyName);\n        RaisePropertyChanged(YearOneByPercentagePropertyName);\n    }\n}\n\npublic const string YearOneByPercentagePropertyName = "YearOneByPercentage";\npublic int YearOneByPercentage\n{\n    get\n    {\n        return _yearOneByPercentage;\n    }\n\n    set\n    {\n        if (_yearOneByPercentage == value)\n        {\n            return;\n        }\n\n        _yearOneByPercentage = value;\n        _yearOneByIndex = 0;\n\n        RaisePropertyChanged(YearOneByIndexPropertyName);\n        RaisePropertyChanged(YearOneByPercentagePropertyName);\n    }\n}	0
9731961	9731866	Use value of passwordbox as a variablein c#	private void loginbutton_Click(object sender, RoutedEventArgs e)\n{\n    usr = textBox1.Text;\n    String pass = textBox2.Password;\n}	0
28808221	28807871	Convert value/type string pair to enumeration value in C#	var vals = Enum.GetValues(Type.GetType("Egypt"));	0
10455246	9964555	How can I update the value of a Label control periodically?	private void timer1_Tick(object sender, EventArgs e)\n{        \n      labelWarningMessage.Text = "";\n      labelWARNING.Visible = false;\n}	0
32366842	32366783	Retrurn list of objects matching by property	return Resoults.Where(p=>p.CurrentID ==ProperID.CurrentID).ToList();	0
5508410	5508392	Two dimension array to single dimension and back again	int x = index % width;\nint y = index / width;	0
20498297	9282318	C# Pull Report out of a DLL and put it in a Report Viewer	MyReportViewer.Reset();	0
5962906	5962884	How to catch SQLException in C#?	catch (SqlException ex)\n    {\n        for (int i = 0; i < ex.Errors.Count; i++)\n        {\n            errorMessages.Append("Index #" + i + "\n" +\n                "Message: " + ex.Errors[i].Message + "\n" +\n                "LineNumber: " + ex.Errors[i].LineNumber + "\n" +\n                "Source: " + ex.Errors[i].Source + "\n" +\n                "Procedure: " + ex.Errors[i].Procedure + "\n");\n        }\n        Console.WriteLine(errorMessages.ToString());\n    }	0
27543653	27543616	Return row with minimum value using Linq	return ProductTerms.OrderBy(t => t.MinTermDuration).FirstOrDefault();	0
2236457	2236432	Write StringBuilder to Stream	using (var memoryStream = new MemoryStream())\nusing (var writer = new StreamWriter(memoryStream ))\n{\n    // Various for loops etc as necessary that will ultimately do this:\n    writer.Write(...);\n}	0
33497226	33495208	Mongodb:Fail to get GridFSFileInfo by ObjectID, but succeed by filename	var filter = Builders<GridFSFileInfo>.Filter.Eq("_id", gridfsObjectID);	0
3667613	3666678	How do you respond ONCE to a user selecting a range in a ListView control?	bool listUpdated = false;\n\n    private void listView1_SelectedIndexChanged(object sender, EventArgs e) {\n        if (!listUpdated) {\n            this.BeginInvoke(new MethodInvoker(updateList));\n            listUpdated = true;\n        }\n    }\n\n    private void updateList() {\n        listUpdated = false;\n        // etc...\n    }	0
10971981	10971885	C# create file with same name as folder name, with extension	string path = @"C:\Windows\System32\";\nFileInfo fi = new FileInfo(path);\nstring outFile = fi.DirectoryName + ".xyz";	0
7573320	7573187	Unable to populate lsitbox in asp.net web application	foreach (DataRow row in ds.Tables[0].Rows)\n            {\n\n                samplelist.Add(row["WORKSTATION_ID"].ToString());\n\n            }\n\n            listbox1.DataSource = samplelist;\n    listbox1.DataBind();	0
12909559	12909531	Custom order by in sql query	ORDER BY\nCASE Category\n   WHEN 'Pettycash' THEN '1'\n   WHEN 'DailyExpense' THEN '2'\n   WHEN 'Home Expense' THEN '3'\n   WHEN 'Fair Expense' THEN '4'\n   WHEN 'Cash Expense' THEN '5'\n   ELSE '6' \nEND	0
4759360	4759145	Copying one list to another	for (int i = 0; i <= (_eam.No_of_Vehicles - 1); i++) {\n\n   _parkingVehicle = new VehicleViewModel(); // Or any other class that is your implementation\n   // The actual type of _parkingVehicle is not clear from your question\n\n   _parkingVehicle.DriverName = _eam.DriverNameList[i].DriverName;\n   // Rest of your code	0
8317808	8317671	Append Enum Flags to a Parameter in a Loop (Bitwise Appending)	string protectionOptionsString = "NoPrevention, PreventPrinting";\nmyObj.Protection |= (ProtectionOptions)Enum.Parse(typeof(ProtectionOptions), protectionOptionsString);	0
6545841	6545266	How can i use multithreading to handle a list in C#?	IEnumerable<Entity> entities;\nint rangeStartIndex = 0;\nint rangeLength = 1000;\n\ndo\n{\n    entities = dataContext.Entities\n        .Skip(rangeStartIndex)\n        .Take(rangeLength);\n\n    Parallel.ForEach(\n        entities,\n        item =>\n        {\n            // Process a single entity in the list\n        });\n\n    using (var tran = new TransactionScope())\n    {\n        // Persist the entities in the database\n        tran.Complete();\n    }\n\n    rangeStartIndex += rangeLength;\n\n} while (entities.Any());	0
24060590	24043918	TFS Build not copying files correctly at end of build	IF "$(BuildingInsideVisualStudio)"=="true" ( copy command here )	0
15227310	15211275	Running command from ASP.NET App Pool Identity	using (var proc = new Process())\n        {\n            proc.StartInfo.FileName = Server.MapPath("~/Testing/Demo/MyEXE.exe");\n            proc.StartInfo.Arguments = String.Format("\"{0}\"", commandFile);\n            proc.StartInfo.WorkingDirectory = savePath;\n            proc.Start();\n            proc.WaitForExit();\n        }	0
13428153	13423545	Dynamically modify RouteValueDictionary	for (int i = 0; i < methodParameters.Length; i++)\n{\n    // I. instead of this\n\n    //values.First(x => x.Key == unMappedList.ElementAt(i).Key)\n    //    .Key = methodParameters.ElementAt(i).Name; \n    //above doesn't work, but even if it did it wouldn't do the right thing\n\n    // II. do this (not so elegant but working;)\n    var key = unMappedList.ElementAt(i).Key;\n    var value = values[key];\n    values.Remove(key);\n    values.Add(methodParameters.ElementAt(i).Name, value);\n\n    // III. THIS is essential! if statement must be moved after the for loop\n    //return true;\n}\nreturn true; // here we can return true	0
2334002	2333835	extract all email address from a text using c#	public static void emas(string text)\n        {\n            const string MatchEmailPattern =\n           @"(([\w-]+\.)+[\w-]+|([a-zA-Z]{1}|[\w-]{2,}))@"\n           + @"((([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\."\n             + @"([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])\.([0-1]?[0-9]{1,2}|25[0-5]|2[0-4][0-9])){1}|"\n           + @"([a-zA-Z]+[\w-]+\.)+[a-zA-Z]{2,4})";\n            Regex rx = new Regex(MatchEmailPattern,  RegexOptions.Compiled | RegexOptions.IgnoreCase);\n            // Find matches.\n            MatchCollection matches = rx.Matches(text);\n            // Report the number of matches found.\n            int noOfMatches = matches.Count;\n            // Report on each match.\n            foreach (Match match in matches)\n            {\n                Console.WriteLine(match.Value.ToString());\n            }\n        }	0
28965134	28964934	log4net inserting (null) into custom column	log4net.GlobalContext.Properties["CustomColumn"] = DBNull.Value;	0
6199646	6199574	Keyboard shortcut to close the Find and Replace dialog	Command Name            | Short-Cut Key  | Description\n----------------------- | -------------- | -------------------------------\nWindow.CloseToolWindow  | SHIFT + ESC    | Closes the current tool window	0
21401541	21384561	How to process files in directory concurrently in .net	while (true)\n    {\n        try\n        {\n            FileInfo[] files = dir.GetFiles(m_fileTypes);\n            Partitioner<FileInfo> partitioner = Partitioner.Create(files, true);\n            Parallel.ForEach(partitioner, f => \n            {\n                try\n                {\n                    XmlMsg msg = factory.getMessage(messageType);\n                    try\n                    {\n                        msg.loadFile(f.FullName);\n                        MsgQueue.Enqueue(new Tuple<XmlMsg, FileInfo>(msg, f));\n                    }\n                    catch (Exception e)\n                    {\n                        handleMessageFailed(f, e.ToString());\n                    }\n                }\n            });\n            //Added check to wait for queue to deplete before \n            //re-scanning the directory\n            while (MsgQueue.Count > 0)\n            {\n                System.Threading.Thread.Sleep(5000);\n            }\n        }\n    }	0
14783673	14783406	Deserializing nested xml into C# objects	XmlSerializer ser = new XmlSerializer(typeof(Users));\nvar u = (Users)ser.Deserialize(stream);\n\n\n[XmlRoot("users")]\npublic class Users\n{\n    [XmlElement("user")]\n    public User[] UserList { get; set; }\n}\n\npublic class User\n{\n    [XmlElement("name")]\n    public string Name { get; set; }\n\n    [XmlArray("orders"),XmlArrayItem("order")]\n    public Order[] OrderList { get; set; }\n}\n\n[XmlRoot("order")]\npublic class Order\n{\n    [XmlElement("number")]\n    public string Number { get; set; }\n}	0
251220	251198	How to restrict the CPU usage a C# program takes?	Thread.CurrentThread.Priority = ThreadPriority.Lowest;	0
34061681	34061603	C# call variables by formatting their name on the fly	var variablename = "v" + i;\nMethodInfo method = product.GetType().GetMethod(variablename);\nobject result = method.Invoke(product, new object[] {}); // pass in the parameters if you need to	0
5947723	5947663	How to redirect from one ASP.NET page to another	Response.Redirect()	0
12189050	987332	How to Automate Testing of Medium Trust Code	public class SomeTests : MarshalByRefObject\n{\n    [PartialTrustFact]\n    public void Partial_trust_test1()\n    {\n        // Runs in medium trust\n    }\n}\n\n// Or...\n\n[PartialTrustFixture]\npublic class MoreTests : MarshalByRefObject\n{\n    [Fact]\n    public void Another_partial_trust_test()\n    {\n        // Runs in medium trust\n    }\n}	0
24007286	23947420	how to convert full word match query from sql to ef	string t = "parrothead";\nList<titles> tData = db.titles_data.Where(\n    o=> o.title.Contains(" " + t + " ") || \n    o.title.StartsWith(t + " ") || \n    o.title.EndsWith(" "+ t)).ToList();	0
11938166	11938121	Generate unique hash from filename	string ComputeFourDigitStringHash(string filepath)\n{\n     string filename = System.IO.Path.GetFileNameWithoutExtension(filepath);\n     int hash = filename.GetHashCode() % 10000;\n     return hash.ToString("0000");\n}	0
28084647	27935658	Captions only working in full screen	var convertedURI = new Uri("file:///" + Application.StartupPath +\n                           "\\Wildlife.wmv").AbsoluteUri;\naxVLCPlugin21.playlist.add(convertedURI);\naxVLCPlugin21.playlist.play();	0
32919928	32919886	how to get each item without using a loop from string array in c#	for(int i=0; i<itmnme.Length; i++)\n{\n    var name = itmnme[i];\n    var quantity = qntity[i];\n    var price = price[i];\n    // do what you need with these values\n}	0
10918985	10918893	How to keep selected item in listview when new items are added?	TextReader reader = new StringReader(richTextBox1.Text);\n        string[] strItems = null;\n        while (reader.Peek() != -1)\n        {\n            string nextRow = reader.ReadLine();\n            if (!listView1.Items.ContainsKey(nextRow.GetHashCode().ToString()))\n            {\n               ListViewItem item = new ListViewItem();\n               item.Name = nextRow.GetHashCode().ToString();\n               strItems = nextRow .Split("-".ToCharArray());\n               item.Text = strItems[0].ToString();\n               item.SubItems.Add(strItems[1].ToString());\n               item.SubItems.Add(strItems[2].ToString());\n               item.SubItems.Add(strItems[3].ToString());\n               item.SubItems.Add(strItems[4].ToString());\n               listView1.Items.Add(item);\n            }\n        }	0
7110841	7110762	How do I create a single list of object pairs from two lists in C#?	public static IEnumerable<Tuple<T, U>> CombineWith<T, U>(this IEnumerable<T> first, IEnumerable<U> second)\n{\n    using (var firstEnumerator = first.GetEnumerator())\n    using (var secondEnumerator = second.GetEnumerator())\n    {\n        bool hasFirst = true;\n        bool hasSecond = true;\n\n        while (\n            // Only call MoveNext if it didn't fail last time.\n            (hasFirst && (hasFirst = firstEnumerator.MoveNext()))\n            | // WARNING: Do NOT change to ||.\n            (hasSecond && (hasSecond = secondEnumerator.MoveNext()))\n            )\n        {\n            yield return Tuple.Create(\n                    hasFirst ? firstEnumerator.Current : default(T),\n                    hasSecond ? secondEnumerator.Current : default(U)\n                );\n        }\n    }\n}	0
6689431	6689069	C# Populating a treeview from database results	List<string> earnings = new List<string>() { "Housing Allowance", "Mobile Phone Allowance", "Mileage Allowance" };\nList<string> deductions = new List<string>() { "Housing Ban", "Mobile Phone Ban", "Mileage Ban" };\n\ntreeView1.Nodes.Add("Component");//adding root node\ntreeView1.Nodes[0].Nodes.Add("Earnings");//adding earnings child node\ntreeView1.Nodes[0].Nodes.Add("Deductions");//adding deduction child node\n\n//adding all earnings to "Earnings" node\nforeach (string earning in earnings)\n{\n    treeView1.Nodes[0].Nodes[0].Nodes.Add(earning);\n}\n\n//adding all deductions to "Deductions" node\nforeach (string deduction in deductions)\n{\n    treeView1.Nodes[0].Nodes[1].Nodes.Add(deduction);\n}	0
16800091	16799645	Linq Remove results with ALL statement	var uIdToRemove = mandatoryusers.GroupBy(m => m.Uid)\n                    .Where(g => mandatory.Except(g.Select(s => s.CertificateValue)).Any())\n                    .Select(g => g.Key).ToList();\n\nmandatoryusers.RemoveAll(x => uidToRemove.Contains(x.Uid));	0
10523371	10520424	How can I consolidate my dll project settings into my main exe.config file in Visual Studio 2010 for a C# application?	ExeConfigurationFileMap map = new ExeConfigurationFileMap();\nmap.ExeConfigFilename = "..\\mydll.config";\nConfiguration config = ConfigurationManager.OpenMappedExeConfiguration(map,  ConfigurationUserLevel.None);\nAppSettingsSection section = (AppSettingsSection)config.GetSection("appSettings");	0
11196284	11195441	RavenDB - Optional where clause	var where = new List<Expression<Func<Person, bool>>>();\n\nif (!string.IsNullOrWhitespace(lastName))\n    where.Add(p => p.LastName == lastName);\n\nif (!string.IsNullOrWhitespace(firstName))\n    where.Add(p => p.FirstName == firstName);\n\n// etc...\n\nvar query = session.Query<Person>();\n\nforeach (var clause in where)\n    query = query.Where(clause);\n\nvar results = query.ToList();	0
27622302	27605162	String formatting with spaces	String.Format	0
4286062	4285747	The statically inserted items in combobox doubles on button click for more than once	public void SetOperationDropDown()\n{\nif(CmbOperations.Items.Count == 0)\n{\n//ByDefault the selected text in the cmbOperations will be -SELECT OPERATIONS-. \ncmbOperations.SelectedItem = "-SELECT OPERATIONS-"; \n//This is for adding four operations with value in operation dropdown \ncmbOperations.Items.Insert(0, "PrimaryKeyTables"); \ncmbOperations.Items.Insert(1, "NonPrimaryKeyTables"); \ncmbOperations.Items.Insert(2, "ForeignKeyTables"); \ncmbOperations.Items.Insert(3, "NonForeignKeyTables"); \ncmbOperations.Items.Insert(4, "UPPERCASEDTables"); \ncmbOperations.Items.Insert(5, "lowercasedtables"); \n\n\n}\nelse\n{\nint? cbSelectedValue = null;\nif(!string.IsNullOrEmpty(cmbOperations.SelectedValue))\ncbSelectedValue = convert.toInt32(cmbOperations.SelectedValue);\n}\n//load your combo again\nif(cbSelectedValue != null)\ncmbOperations.SelectedValue = cbSelectedValue.ToString();\n}	0
1306151	1306018	Getting my screens' name in c#	SelectQuery q = new SelectQuery("SELECT Name, DeviceID, Description FROM Win32_DesktopMonitor");\nusing(ManagementObjectSearcher mos = new ManagementObjectSearcher(q))\n{\n    foreach(ManagementObject mo in mos.Get())\n    {\n        Console.WriteLine("{0}, {1}, {2}",\n            mo.Properties["Name"].Value.ToString(),\n            mo.Properties["DeviceID"].Value.ToString(),\n            mo.Properties["Description"].Value.ToString());\n    }\n}	0
11764031	11764008	How can I change a form's color and size in C#?	this.BackColor = Color.Red;\nthis.Size = new Size(1600, 900);	0
32126243	32125974	Set Form.Text at designer time to a non-constant string	App.config	0
5322277	5322246	Type parameter to variable	item.GetValue(obj, null);	0
14369225	14369175	How do I change an object in a form's properties using a function?	private void SetText(Control control, String text)\n{\n    control.Text = text;\n}	0
8046257	8041431	How to make Fluid Drag equation not framerate dependent	//In globals / initialization:\nVector2 Position;\nVector2 Speed;\nVector2 ThrustForce;\nfloat Coefficient = 0.009f;\nfloat PreviousDrag = 0.000f;\n\n//In the update loop\n//DeltaTime is a float based upon how much of a second passed\nVector2 AccelerationToApply = ThrustForce * DeltaTime + PreviousDrag * DeltaTime;\nVector2 NewSpeed = Speed + AccelerationToApply;\nPreviousDrag = Coefficient * NewSpeed * NewSpeed;\nSpeed = NewSpeed;	0
9836176	9835937	I want to delete row in repeater	e.Item.Visible = false	0
16612754	16611148	Getting/setting the value of an integer inside a Razor view	public ActionResult SomeActionMethod(FormCollection formCollection)\n{\n  foreach (var key in formCollection.AllKeys)\n  {\n    var value = formCollection[key];\n  }\n// or \nvar color=formCollection["color"];\n}	0
31689920	31689535	Regular expression encoded wrongly in another server	[RegularExpression("^([^/\\*?:\\u0022\\u003c\\u003e|]*)$", ....	0
32821509	32819822	Print the selected week from a Calendar control on a label.	// Since Sunday has the index of 0, and you want the week to start from Monday,\n// we need to shift the numbers around so that Monday is 0 instead.\nint dayNumber = ((int)Calendar1.SelectedDate.DayOfWeek + 6) % 7;\n\nDateTime monday = Calendar1.SelectedDate.AddDays(-dayNumber);\nDateTime sunday = Calendar1.SelectedDate.AddDays(6 - dayNumber);\n\nLabel3.Text = string.Format(\n    "{0} - {1}",\n    monday.ToShortDateString(),\n    sunday.ToShortDateString());	0
19969931	19969693	Launch WPF application using Process.Start	Process proc = new Process();\nproc.StartInfo.FileName = programPath;\nproc.StartInfo.WorkingDirectory = Path.GetDirectoryName(programPath);\nproc.Start();	0
19387431	19387086	How to set up TcpListener to always listen and accept multiple connections?	while (true)\n{\n    Socket client = listener.AcceptSocket();\n    Console.WriteLine("Connection accepted.");\n\n    var childSocketThread = new Thread(() =>\n    {\n        byte[] data = new byte[100];\n        int size = client.Receive(data);\n        Console.WriteLine("Recieved data: ");\n        for (int i = 0; i < size; i++)\n            Console.Write(Convert.ToChar(data[i]));\n\n        Console.WriteLine();\n\n        client.Close();\n    });\n    childSocketThread.Start();\n}	0
14939333	14939028	Find and replace several words without affecting future replacements	var pattern = "(" + String.Join("|", words.Select(w => Regex.Escape(w))) + ")";\n// e.g. (word1|word2|word3|word4)\nvalue = Regex.Replace(\n    value,\n    pattern,\n    "<b>$1</b>",\n    RegexOptions.IgnoreCase);	0
2113714	2113684	find inside array of objects	list.Where(o => o.Id == 10);	0
13088349	13084936	How to move and rotate group of polygons in xna?	Stack<Matrix> matrixStack = new Stack<Matrix>();\n...\nmatrixStack.Push( armMatrix );\n...\nbasicEffect.World = matrixStack.Peek();\nforeach (EffectPass pass in basicEffect.CurrentTechnique.Passes)\n{\n    pass.Apply();\n\n    graphics.GraphicsDevice.DrawPrimitives(...);\n}\nbasicEffect.End();\n...\nmatrixStack.Pop();	0
27343401	27342862	Xpath select all tr without table with id=x	var q = \nxml.XPathSelectElements(@"/tr[not(descendant::table[@id = 'WHITE_BANKTABLE'])]");	0
10538113	10537914	Detecting misuse of lambdas with static analysis in VS2010	static void Main(string[] args)\n    {\n        var items = new[] { 1, 2, 3 };\n        var list = items.Select(i => Foo(i)).ToList(); // R# suggests "Convert to method group"\n    }\n\n    static int Foo(int i)\n    {\n        return i;\n    }	0
6553242	6552991	Is there a better solution to this List<DateTime> sorting?	menuItems = dates\n     .GroupBy(x => new DateTime(x.Year, x.Month, 1))\n     .Select(x=> new{Date = x.Key, Count = x.Count()})\n     .OrderByDescending(x => x.Date)\n     .Select(x => new ArchiveMenuItem(streamUrl, \n                                      x.Date.Month, \n                                      x.Date.Year, \n                                      x.Count))\n     .ToList();	0
26895459	26895016	Get View outside Controller Context	public string ToHtml(string pView, ControllerContext context = null)\n{\n    if (context == null)\n        context = ControllerContext;\n\n    using (var sw = new StringWriter())\n    {\n        var viewResult = ViewEngines.Engines.FindPartialView(context, pView);\n        var viewContext = new ViewContext(context, viewResult.View, ViewData, TempData, sw);\n        viewResult.View.Render(viewContext, sw);\n        viewResult.ViewEngine.ReleaseView(context, viewResult.View);\n        return sw.GetStringBuilder().ToString();\n    }\n}	0
29209502	29208695	VS2008 (Windows CE) auto-resize dataGrid Column width	dgLatestPositions.DataSource = items;\n\n        DataGridTableStyle tableStyle = new DataGridTableStyle();\n        tableStyle.MappingName = items.GetType().Name;\n\n        // Column 1\n        DataGridTextBoxColumn tbcCoding= new DataGridTextBoxColumn();\n        tbcCoding.Width = 100;\n        tbcCoding.MappingName = "Coding";\n        tbcCoding.HeaderText = "Coding";\n        tableStyle.GridColumnStyles.Add(tbcCoding);\n\n        // Column 2\n        DataGridTextBoxColumn tbcAmount = new DataGridTextBoxColumn();\n        tbcAmount .Width = 100;\n        tbcAmount .MappingName = "Amount";\n        tbcAmount .HeaderText = "Amount";\n        tableStyle.GridColumnStyles.Add(tbcAmount );\n\n        dgLatestPositions.TableStyles.Clear();\n        dgLatestPositions.TableStyles.Add(tableStyle);	0
14366896	14357044	How can I add a timer on Windows Phone 7.1?	DispatcherTimer timer = new DispatcherTimer();\n\n        timer.Tick +=\n            delegate(object s, EventArgs args)\n            {\n                TimeSpan time = (DateTime.Now - App.StartTime);\n\n                this.timenow.Text = string.Format("{0:D2}:{1:D2}:{2:D2}", time.Hours, time.Minutes, time.Seconds);\n            };\n\n        timer.Interval = new TimeSpan(0, 0, 1); // one second\n        timer.Start();	0
14549118	14527233	CreateStreamedFileFromUriAsync: How can i pass a IRandomAccessStreamReference?	IRandomAccessStreamReference thumbnail =\n    RandomAccessStreamReference.CreateFromUri(new Uri(remoteUri));\nIAsyncOperation<StorageFile> file1 =\n    StorageFile.CreateStreamedFileFromUriAsync("duyuru.pdf", new Uri(remoteUri), thumbnail);	0
16987239	16366450	Controlling Group order in a Kendo UI Grid	[ \n    { \n      'Name': 'Alice', \n      'Rank': 10, \n      'RankName': '<span class="myHiddenClass">10</span>Alice', \n      ... (other fields)\n    },  \n    { \n      'Name': 'Bob', \n      'Rank': 9, \n      'RankName': '<span class="myHiddenClass">09</span>Bob', \n      ... (other fields)\n    },  \n    { \n      'Name': 'Eve', \n      'Rank': 11, \n      'RankName': '<span class="myHiddenClass">11</span>Eve', \n      ... (other fields)\n    } \n    ... (Multiple Alice / Bob / Eve records)\n]	0
10090384	10090272	Check a checkbox and get its sibling from listview row	private void CompanyCheckboxClicked(object sender, RoutedEventArgs e)\n{\n    CheckBox checkBox = sender as CheckBox;\n    Row row = checkBox.DataContext as Row;\n    ...\n}	0
14381264	14380517	attaching a file to a message	Attachment attachment = new Attachment(attachmentPath);\nmsg.Attachments.Add(attachment);	0
20738284	20734800	How to get hold event item of Grouped LongListSelector?	private void LLST_Hold(object sender, System.Windows.Input.GestureEventArgs e)\n{\n   if (LLST.SelectedItem != null)\n   {\n      ItemType item = LLST.SelectedItem as ItemType;\n      // do some stuff\n   }\n}	0
32125486	32113068	How to insert an entity in a specific layout in Autocad using .net?	using (Transaction tr = db.TransactionManager.StartTransaction())\n{\n    DBDictionary layoutDic\n        = tr.GetObject(\n                        db.LayoutDictionaryId,\n                        OpenMode.ForRead,\n                        false\n                      ) as DBDictionary;\n\n    foreach (DBDictionaryEntry entry in layoutDic)\n    {\n        ObjectId layoutId = entry.Value;\n\n        Layout layout\n            = tr.GetObject(\n                            layoutId,\n                            OpenMode.ForRead\n                          ) as Layout;\n\n        ed.WriteMessage(\n            String.Format(\n                            "{0}--> {1}",\n                            Environment.NewLine,\n                            layout.LayoutName\n                         )\n                       );\n    }\n    tr.Commit();\n}	0
2417124	2416963	How to create an Explorer-like folder browser control?	windows explorer tree view C#	0
15086633	15044243	Insert new child node in an existing XML	originalXml.Save(Server.MapPath("xmlTechReportDetails.xml"));	0
8272792	8272733	How do I turn a binary string into a float or double?	string bstr = "01010101010101010101010101010101";\nlong v = 0;\nfor (int i = bstr.Length - 1; i >= 0; i--) v = (v << 1) + (bstr[i] - '0');\ndouble d = BitConverter.ToDouble(BitConverter.GetBytes(v), 0);\n// d = 1.41466386031414E-314	0
3954284	3954275	How best to block multiple "counts" on a counter?	if (Session["HasCountedThisVisitor"] == null) \n{\n    counter++; \n    Session["HasCountedThisVisitor"] = true;\n}	0
820868	820514	Microsoft WinForm ReportViewer from List	var reportViewer = New ReportViewer();\nvar reportDataSource = New ReportDataSource("MyNS_Dog", MyDogs);\nreportViewer.LocalReport.DataSources.Add(reportDataSource);	0
1491861	1491657	converting from byte to 7 bit byte	var content = File.ReadAllBytes("c:\yourpath");\nvar base64Content = Convert.ToBase64String(content);\nvar base64Array = System.Text.Encoding.ASCII.GetBytes(base64Content);	0
709641	709540	Capture multiple key downs in C#	[DllImport ("user32.dll")]\npublic static extern int GetKeyboardState( byte[] keystate );\n\n\nprivate void Form1_KeyDown(object sender, KeyEventArgs e)\n{\n   byte[] keys = new byte[256];\n\n   GetKeyboardState (keys);\n\n   if ((keys[(int)Keys.Up] & keys[(int)Keys.Right] & 128 ) == 128)\n   {\n       Console.WriteLine ("Up Arrow key and Right Arrow key down.");\n   }\n}	0
14823385	14821129	Simple.Data One Direction Join on a Table Twice	dynamic sender;\ndynamic recipient;\nvar messages= db.Messages.All(db.Messages.To_Id == currentUser.Id || db.Messages.From_Id == currentUser.Id)\n    .Join(db.Users.As("Sender"), out sender).On(sender.Id == db.Messages.From_Id)\n    .Join(db.Users.As("Recipient"), out recipient).On(recipient.Id == db.Messages.To_Id)\n    .With(sender)\n    .With(recipient);\nreturn messages;	0
32113	32103	how do you programatically invoke a listview label edit	ListViewItem::BeginEdit();	0
2800817	2800690	default value in web service wsdl in asp.net	[System.ComponentModel.DefaultValue(0)]    \npublic int EmpId\n{\nget;set;\n}	0
24420328	24297357	Errors only in release mode (Windows store app C# / XAML)	#IF DEBUG\n...\n#ENDIF	0
6246530	6246498	How do I use a socket proxy in C# webbrowser?	string serverName = ""; // your proxy server name\nstring port = ""; // your proxy port\n\nvar key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Internet Settings", true);\nkey.SetValue("ProxyServer", serverName + ":" + port);\nkey.SetValue("ProxyEnable", 1);	0
30510800	30510608	ApiController json from string	var jsonResponse = JObject.Parse(await response.Content.ReadAsStringAsync());\nreturn Json(jsonResponse);	0
25908722	25907752	How to hide or remove UITableViewCell with it's content temporarily	- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {\n    UITableViewCell *cell = [super tableView:tableView cellForRowAtIndexPath:indexPath];\n    if(indexPath.row == 5 || indexPath.row == 7) {\n        cell.clipsToBounds = YES;\n    }\n    return cell;\n}	0
1722343	1722334	Extract only right most n letters from a string	string SubString = MyString.Substring(MyString.Length-6);	0
22128330	21222329	Export more than 100,000 rows from wpf datagrid to Excel - C# Microsoft.Office Interop 14	System.Diagnostics.Process.Start(completeFilename);	0
11564635	11563535	How to catch PowerShell function call from c#	rs.RunspaceConfiguration.Cmdlets.Append(New CmdletConfigurationEntry("testfunction", GetType(TestFuncitonCmdlet), Nothing))	0
9129380	9128554	getting data from XML using asp.net Vb.net	XDocument xml = XDocument.Load("file.xml");\n  var firstElement = xml.Descendants().Where(x => x.Name == "Node" && x.Attribute("id").Value=="15").FirstOrDefault();\n  var lastElement = xml.Descendants().Where(x => x.Name == "Node" && x.Attribute("id").Value == "30").FirstOrDefault();\n  var response = firstElement.NodesAfterSelf().Where(x => lastElement.NodesBeforeSelf().Contains(x));	0
6953671	6953549	How to catch any type of application exit?	Process.Exited	0
1365083	1365070	Add data to a Table<T>?	Table<TEntity>.InsertOnSubmit	0
13560410	13559917	Retrieving and parse XML from the link programmaticaly	Stream responseStream = null;\n        try\n        {\n            WebRequest request = WebRequest.Create("http://www.website.com/XMLRetrieval.ascx?arg1=value&arg2=value");\n            WebResponse webResponse = request.GetResponse();\n            responseStream = webResponse.GetResponseStream();\n        }\n        catch (Exception e)\n        {\n            return null;\n        }\n\n        if (responseStream != null)\n        {\n            return new XPathDocument(responseStream);\n        }	0
19116129	19098569	Allow leading zeros on a worksheet with EP Plus	codeSheet.Cells["A:D"].Style.Numberformat.Format = "@";	0
1542996	1542978	Loop Problem: Assign data to different strings when in a loop	var format="{0}, {1} {2}. How are you?";\n\n//string Greeting = "Hello"\n//string Name = "Allan"\n//string Company = "IBM"\n\n//all of it happening in a loop.\nstring data = ...; //I think you have an array of strings separated by ,\n\nforeach( va s in data){\n{\n    //string s = data[i];//.ToString(); - it is already a string array\n    string[] words = data[i].Split(',');\n\n    Console.WriteLine(format, words[0], words[1], words[2]);\n}	0
28555720	28555555	How to share text in installed social media in windows phone 8?	ShareStatusTask sst= new ShareStatusTask();\nsst.Status = "Lorem ipsum dolor sit amet";\nsst.Show();	0
6955093	6954988	C#: Definition of the scope of variables declared in the initialization part of for-loops?	int i;\n\nfor (int i = 0; i < 10; i++)\n{\n}\n\ni = 13;	0
21664201	21663723	something wrong with gridview	protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n        if (e.Row.RowType == DataControlRowType.DataRow)\n        {\n            e.Row.Cells[0].Width = 100;\n            e.Row.Cells[1].Width = 150;\n        }\n}	0
399574	399532	How can I grab a double key stroke in .NET	bool mSeenCtrlM;\n\nprotected override bool ProcessCmdKey(ref Message msg, Keys keyData) {\n  if (keyData == (Keys.Control | Keys.M)) {\n    mSeenCtrlM = !mSeenCtrlM;\n    if (!mSeenCtrlM) {\n      MessageBox.Show("yada");\n    }\n    return true;\n  }\n  mSeenCtrlM = false;\n  return base.ProcessCmdKey(ref msg, keyData);\n}	0
8143117	8143096	Nested loop through 2 large sets of data	Dictionary<TypeOfKey, SomeObject>	0
5358264	5358261	How to get month name and am/pm in lowercase	DateTime.Now.ToString("MMMM h:m tt").ToLower();	0
8065897	8057751	Pass a dynamic variable in a static parameter of a method in C# 4	public interface ISomeStaticInterface{\n      int IntProperty {get;}\n      string StringProperty {get;}\n}\n...\nvar myVar = new SomeDynamicObjectImplementer().ActLike<ISomeStaticInterface>();\nmethod(myVar.IntProperty, myVar.StringProperty);	0
19010445	19009550	How to use SqlBuilder	using StackExchange.Profiling.Helpers.Dapper;	0
10498543	10497102	How to stop base static events/actions firing in other derived classes	public abstract class Entity\n{\n    private static Dictionary<Type, Action> Subscribers\n         = new Dictionary<Type, Action>();\n\n    internal virtual void OnSaved()\n    {\n        OnSaved(GetType());\n    }\n\n    private OnSaved(Type type)\n    {\n        Action subscribed;\n        Subscribers.TryGetValue(type, out subscribed);\n        if (subscribed != null)\n            subscribed();\n    }\n\n    public Subscribe(Type type, Action action)\n    {\n        Action subscribed;\n        Subscribers.TryGetValue(type, out subscribed);\n        Subscribers[type] = subscribed + action;\n    }\n\n    public Unsubscribe(Type type, Action action)\n    {\n        Action subscribed;\n        Subscribers.TryGetValue(type, out subscribed);\n        Subscribers[type] = subscribed - action;\n    }\n}	0
22696281	22696154	C# Dice game, 2 dice, each dice rolls 50 times	for (int throw = 1; throw <= 100; throw++)\n{\n    if(x.Next(0,2) == 0)\n        Dice1[x.Next(1, 7)]++;\n    else\n        Dice2[x.Next(1, 7)]++;\n}	0
3522814	3513162	Add Signing Time to PKCS7 Signed CMS?	cmsSigner.SignedAttributes.Add(new Pkcs9SigningTime());	0
13419706	13419676	Assigning the Model to a Javascript variable in Razor	var jsData = @Html.Raw(Json.Encode(Model.MyCollection));	0
22304150	22304021	How to require text in a Textbox?	String strName = txtName.Text.Trim(); //add trim here\nString strEmail = txtEmail.Text;\nBoolean blnErrors = false;\n\nif (string.IsNullOrWhiteSpace(sstrName)) //this function checks for both null or empty string.\n{\n    string script = "alert(\"Name Field Is Required!\");";\n    ScriptManager.RegisterStartupScript(this, GetType(), "ServerControlScript", script, true);\n    txtName.Focus();\n    return;//return from the function as there is an error.\n}\n\n//continue as usual .	0
5314992	5314951	How to render encoded tags as proper HTML, rather than text?	String Input = "investment professionals.&lt;BR /&gt;&lt;BR /&gt; blah blah blah";\n\n    String Output = Server.HtmlDecode(Input);	0
25045232	25044960	ReadLine() from two sources simultaneously	Task t1 = null, t2 = null;\nwhile(!StartServer.HasExited)\n{\n       if (t1 == null || t1.IsCompleted)\n           t1= Task.Run(() =>  Console.WriteLine(StartServer.StandardOutput.ReadLine()));\n       if (t2 == null || t2.IsCompleted)\n           t2 = Task.Run(() => StartServer.StandardInput.WriteLine(Console.ReadLine()));\n       Task.WaitAny(new[] { t1, t2 });\n}	0
5646668	5646651	Convert string in to number?	int result = Int32.Parse(str.Replace(".", String.Empty));	0
13971550	13971165	Populate Gridview at runtime using textfile	protected void readfile_Click(object sender, EventArgs e)\n    {\n        DataTable table = new DataTable();\n        table.Columns.Add("Row No.");\n        table.Columns.Add("Col No.");\n        table.Columns.Add("Width");\n        table.Columns.Add("Height");\n        table.Columns.Add("Image URL");\n        table.Columns.Add("Description");\n\n        using (StreamReader sr = new StreamReader(@"D:\Temp\fileread\readtext.txt"))\n        {\n            while (!sr.EndOfStream)\n            {\n                string[] parts = sr.ReadLine().Split(',');\n                table.Rows.Add(parts[0], parts[1], parts[2], parts[3], parts[4], parts[5]);\n            }\n        }\n        MyGridView.DataSource = table;\n        MyGridView.DataBind();\n    }	0
18608986	18606818	Sort ListBox (Windows Phone)	//Ascending\nvar a = (from b in xCryptoDB.GetTable<AccountsTable>() select b.Extra).OrderBy(e => e)\n\n//Descending\nvar a = (from b in xCryptoDB.GetTable<AccountsTable>() select b.Extra).OrderByDescending(e => e)	0
25062935	25061975	How to convert the period in a decimal value to something more URL friendly with Regex for news stories	string str = "Dollar Tree to buy Family Dollar for about $8.5 billion";\nstring remove = Regex.Replace(str, @" ", "-");\nstring result = Regex.Replace(remove, @"^(.*?)\$(\d+)\.(\d+)\b(.*)$", "$1$2-point-$3$4");\nConsole.WriteLine(result);\nConsole.ReadLine();	0
31435765	31435543	how to convert UTC dateTime to local datetime	ID     Date/Time UTC          Date/Time Local (would be computed)\nA      2015-10-24T23:45Z      2015-10-25T00:45 (BST)\nB      2015-10-25T00:15Z      2015-10-25T01:15 (BST)\nC      2015-10-25T00:45Z      2015-10-25T01:45 (BST)\nD      2015-10-25T01:15Z      2015-10-25T01:15 (GMT)\nE      2015-10-25T01:45Z      2015-10-25T01:45 (GMT)\nF      2015-10-25T02:15Z      2015-10-25T02:15 (GMT)	0
8785492	8785416	Showing Modal Window while BackgroundWorker runs, without getting STA/MTA issue	this.Dispatcher.BeginInvoke(new Action(() => ProgressDialog.ShowDialog()));	0
27384188	27384126	Running string as a Batch file in c#	Process.Start("cmd.exe", "/c echo \"bla bla\" \n iperf -c 123  ... ... .. ");	0
2653006	2652760	How to convert a gi-normous integer (in string format) to hex format? (C#)	var s = "843370923007003347112437570992242323";\n        var result = new List<byte>();\n        result.Add( 0 );\n        foreach ( char c in s )\n        {\n            int val = (int)( c - '0' );\n            for ( int i = 0 ; i < result.Count ; i++ )\n            {\n                int digit = result[i] * 10 + val;\n                result[i] = (byte)( digit & 0x0F );\n                val = digit >> 4;\n            }\n            if ( val != 0 )\n                result.Add( (byte)val );\n        }\n\n        var hex = "";\n        foreach ( byte b in result )\n            hex = "0123456789ABCDEF"[ b ] + hex;	0
14971496	14971445	Get data based on column name	for (int i = 0; i < dataTable.Rows.Count; i++)\n        {\n            DataRow dr = dataTable.Rows[i]; //Where the RowIndex\n            string a = dr[0].ToString();    //Where the ColumnIndex or ColumnName\n        }	0
7312501	7312361	c# combobox in datagridview	void dataGridView1_EditingControlShowing(object sender,\n            DataGridViewEditingControlShowingEventArgs e)\n        {\n            if (e.Control is ComboBox)\n            {\n                ComboBox cmb = e.Control as ComboBox;\n\n                // here you can work on the ComboBox...\n            }\n        }	0
16471658	16471595	C# compare string ignoreCase	Assert.AreEqual(user1.UserName, user2.UserName, true, CultureInfo.CurrentCulture);	0
19452356	19450818	Create a FSharpMap (of FSharpMap) using GroupBy in LINQ	MyDatabaseService.AspnetDB.SynchronousReturn(\n    context => new FSharpMap<string, FSharpMap<string, string>>(\n        context.aspnet_UsersValues\n            .GroupBy(databaseValue => databaseValue.UserName)\n            .Select(group =>\n                 new Tuple<string, FSharpMap<string, string>>(\n                     group.Key, \n                     new FSharpMap<string, string>(\n                         group.Select(keyValuePair => \n                             new Tuple<string, string>(\n                                 keyValuePair.Key, \n                                 keyValuePair.Value\n                             )\n                         )\n                    )\n                )\n            )\n    )\n)	0
22644629	22644587	How to mock xmlSerializer	public class XmlSerializerWrapper:IXmlSerializerWrapper\n  {\n       private XmlSerializer _serializer;\n\n      //implement some methods that you need from XmlSerializer\n  }	0
13605222	13604998	xml nodes editing based on an xmlElement	int id = 9;\nXDocument xdoc = XDocument.Load(filepath);\nvar student = xdoc.Descendants("student")\n                  .Where(s => (int)s.Element("id") == id)\n                  .SingleOrDefault();\n\nif (student != null)\n{\n    student.Element("first_name").Value = TextBox_firstname.Text;\n    student.Element("last_name").Value = TextBox_lastname.Text;\n    student.Element("DOB").Value = TextBox_dob.Text;\n    student.Element("class").Value = TextBox_class.Text;\n    // etc\n}\n\nxdoc.Save(filepath);	0
11145648	11135838	"cannot insert null value to primary key" error while trying to insert a non-null value	command.CommandType = CommandType.StoredProcedure;	0
9413664	9413421	Caveats Encoding a C# string to a Javascript string	System.Web.HttpUtility.JavaScriptStringEncode(@"aa\bb ""cc"" dd\tee", true);\n== \n"aa\\bb \"cc\" dd\\tee"	0
9431536	9420767	I fail to access Resource image file from code in WPF using pack Uri	new BitmapImage(new Uri("pack://application:,,,/Resources/Images/Output/" \n+ i.ToString() + ".jpg", UriKind.Absolute)));	0
8129864	8129783	Regex to parse sub domain and domain into separate groups	^(https?://)?((?<subdomain>[^\.]+)\.)?(?<domain>[^\./]+\.[^/]+)/?.*$	0
26421834	26421683	Accessing a shared file?	var logFile = (string)null;\nusing (var fileStream = new FileStream(logPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))\n{\n    using (var reader = new StreamReader(fileStream))\n    {\n        logFile = reader.ReadToEnd();\n    }\n}	0
10423084	10423015	NullReferenceException when comparing string read in from a file?	while (findIndex == -1) {\n        userpass = sr.ReadLine();\n        if (userpass == null) break;\n        findIndex = userpass.IndexOf(txtUserName.Text + " " + txtPassword.Password);\n    }	0
3093385	3093347	how can I extract an XML block from an XML document?	XmlNode n = xdoc.SelectSingleNode("//FIRSTNODE");    \nConsole.WriteLine(n.OuterXml);	0
27452096	27450953	Creating Workbooks from templates programatically	//the #region is simply so that if copied and pasted, the code will make sense, and there will be a label encapsulating the specific code lines. *Note it does not affect the results\n#region add workbook from template file\nExcel.Application f;\n//the following line is written assuming that you would have already made sure that excel was in the Running Objects Table (ROT)\nf=(Excel.Application)Marshal.GetActiveObject("Excel.Application");\nf.visible=true;\nf.Workbooks.Add("C:\\...");\n\if there are any questions please comment, I will do my best to explain my own answer\n#endregion	0
28498534	28498167	Removing a random item from a list C#	if (iconButton != null && icons.Count > 0)\n{\n\n\n    int randomNumber = random.Next(0, icons.Count-1);\n    //MessageBox.Show(Convert.ToString(randomNumber));\n    iconButton.Text = icons[randomNumber];\n    //iconButton.ForeColor = iconButton.BackColor;\n    icons.RemoveAt(randomNumber)\n}	0
2027966	2022063	Fire event from Async component in UI thread	public class MyComponent {\n    private AsyncOperation _asyncOperation;\n\n    /// Constructor of my component:\n    MyComponent() {\n        _asyncOperation = AsyncOperationManager.CreateOperation(null);\n    }\n\n    /// <summary>\n    /// Raises an event, ensuring the correct context\n    /// </summary>\n    /// <param name="eventDelegate"></param>\n    /// <param name="args"></param>\n    protected void RaiseEvent(Delegate eventDelegate, object[] args)\n    {\n        if (eventDelegate != null)\n        {\n            _asyncOperation.Post(new System.Threading.SendOrPostCallback(\n                delegate(object argobj)\n                {\n                    eventDelegate.DynamicInvoke(argobj as object[]);\n                }), args);\n        }\n    }\n}	0
24705652	24705583	ASP.Net CheckBoxList Values Insert To Database	protected void SubmitBtn_Click(object sender, EventArgs e)\n{\n    foreach(ListItem li in CheckBoxList1.items)\n    {\n        if(li.Selected)\n        {\n            //insert to database, the value is in item.Value\n        }\n    }\n}	0
19176935	18958566	Unable to use webservice without fiddler	protected override System.Net.WebRequest GetWebRequest(Uri uri)\n    {\n        System.Net.HttpWebRequest webRequest = (System.Net.HttpWebRequest)base.GetWebRequest(uri);\n        webRequest.KeepAlive = false;\n        return webRequest;\n    }	0
25933665	25933465	column data cannot be null c# mysql	OdbcCommand com = new OdbcCommand("insert into audio(data) values(?)", con);\nbyte[] stream = File.ReadAllBytes(@textBoxBrowse.Text);\n    MessageBox.Show(stream.ToString());\n    if (stream.Length > 0)\n    {\n        com.Parameters.AddWithValue("voice", stream);\n        con.Open();\n        int result = com.ExecuteNonQuery();\n        if (result > 0)\n            MessageBox.Show("insert done");\n        con.Close();\n    }\n}	0
20073754	20058581	asp:Button and asp:LinkButton and asp:Button submitting on enter in Chrome	this.Form.DefaultButton = Login1.FindControl("LoginButton").UniqueID;	0
5865669	5865614	List<Int32> Join with a Table in LINQ-SQL Recommendation Request	List<Account> MyMethod(List<int> accounts)\n{\n    return dc.Accounts.Where(x => accounts.Contains(x.AccountID))\n                      .ToList();\n}	0
3865276	3865229	How do I convert this XPath query to LINQ to XML?	var qry = from row in dataNode.Elements("row")\n           select row.Elements("v").ElementAt(1);	0
26434971	26434763	Add Text to an MySQL-Exception	public class ProtonMySQLException : MySQLException\n{\n    public int protonNumber = 0;\n    public string protonSpecialText = string.Empty;\n}	0
21969940	21969855	Send a file over network - Bigger buffer-size than 2 impossible?	int received = nws.Read(...);\na.Write(fileBytes, 0, received);	0
23260424	23260307	How to Write MemoryStream to End of Text File	theFile.Seek(0, SeekOrigin.End)	0
7644818	7644770	How to create a array in 2D array	float[,][] Tile = new float[17, 23][];\n Tile[0, 0] = new float[2] { 1, 2 };	0
20442182	20441593	Using Excel Double Value in C#	string oldString = ds.Tables["Deneme"].Rows[i][j].ToString(); // Old string in addArray.\nstring convertedString = oldString.Replace(".",","); // Replacer for dots.\ndouble convertedDouble = Convert.ToDouble(convertedString); // Convert double now.	0
7865126	186084	How do you add a timer to a C# console application	using System;\nusing System.Threading;\n\npublic static class Program {\n\n   public static void Main() {\n      // Create a Timer object that knows to call our TimerCallback\n      // method once every 2000 milliseconds.\n      Timer t = new Timer(TimerCallback, null, 0, 2000);\n      // Wait for the user to hit <Enter>\n      Console.ReadLine();\n   }\n\n   private static void TimerCallback(Object o) {\n      // Display the date/time when this method got called.\n      Console.WriteLine("In TimerCallback: " + DateTime.Now);\n      // Force a garbage collection to occur for this demo.\n      GC.Collect();\n   }\n}	0
29068773	29068653	Is there a syntactically legal expression that has 2 consecutive identifiers separated only by white space in C#?	Myclass myVariable;	0
25653097	22935921	Querying Azure Table Storage - compare using a static array of values	var rowCompare = String.Format("{0}", DateTime.MaxValue.Ticks - DateTime.UtcNow.Ticks);\nvar items = new []{"1", "6", "10"};\n\nvar filters =\n    items.Select(key => TableQuery.GenerateFilterCondition("PartitionKey", QueryComparisons.Equal, key)).ToArray();\n\nvar combine =\n    filters.Length > 0\n        ? filters[0]\n        : null;\n\nfor (var k = 0; k < filters.Length; k++)\n    combine = TableQuery.CombineFilters(combine, TableOperators.Or, filters[k]);\n\nvar final = TableQuery.GenerateFilterCondition("RowKey", QueryComparisons.GreaterThan, rowCompare);\nif (!string.IsNullOrEmpty(combine))\n    final = TableQuery.CombineFilters(final, TableOperators.And, combine);\n\nvar query = new TableQuery<EntityReport>().Where(final);\n\nvar client = CloudStorageAccount.DevelopmentStorageAccount.CreateCloudTableClient();\nvar table = client.GetTableReference("EntityReports");\nvar result = table.ExecuteQuery(query);	0
6345803	6333451	Display Query results in a DataGrid View	var logDatabaseTableAdapter_queryselect = new SQLiteDataAdapter(("SELECT * from         LogDatabase where LogMessage like '%ERR%'"), "data source=C:\\TMU_Files\\test24.s3db");\n    logDatabaseTableAdapter_queryselect.Fill(logDatabaseDataSet_query.LogDatabase);	0
11091821	11091759	Get data from specific time period	if (fecVuel == fecha && ((hora >= rightnow - 2) && (hora <= rightnow + 2)))	0
11294776	11294423	LINQ Select a List of List with DISTINCT	var result = dbContext.Prices\n    .GroupBy(p => new {p.ItemName, p.ItemTypeName)\n    .Select(g => new Item\n                     {\n                         ItemName = g.Key.ItemName,\n                         ItemTypeName = g.Key.ItemTypeName,\n                         Prices = g.Select(p => new Price \n                                                    {\n                                                        Price = p.Price\n                                                    }\n                                           ).ToList()\n\n                     })\n     .Skip(x)\n     .Take(y)\n     .ToList();	0
4886649	4885050	Outer apply in linq to sql	var query = from mt in db.MasterTable\n             let detailResult = db.UfnGetDetail(mt.x, mt.y, z).SingleOrDefault()...	0
22664937	22664754	Accessing Method in dynamically created User Controls?	class MyView\n{\n    public void CreateControl(string name)\n    {\n        Control picture = new UserControl1();\n        picture.Visible = true;\n        picture.Name = name;\n        picture.Location = new Point(0, 0);\n        picture.Show();\n        flowLayoutPanel1.Controls.Add(picture);\n\n        this.controls.Add(name, picture);\n    }\n\n    public void SetMsg(string name, msg)\n    {\n        ((UserControl1)this.controls[name]).SetMSG(msg);\n    }\n\n    private Dictionary<string, Control> controls = new Dictionary<string, Control>();\n}	0
10949538	10949504	Accessing files using Build Action: Content	Embedded Resource	0
6746555	6746390	Using Arrow Keys to navigate in the Console	ConsoleKeyInfo keyInfo = Console.ReadKey();\nif (keyInfo.Key == ConsoleKey.UpArrow) {\n\n} else if (keyInfo.Key == ConsoleKey.DownArrow) {\n\n} ...	0
18269022	18268619	How to get simple url var with Razor MVC 4?	/BigView/View1	0
1599533	1599359	How to load file icons in a background thread [WPF]	private void _backgroundWorkerLoadImage_DoWork(object sender, DoWorkEventArgs e)\n{\n    BitmapImage img = new BitmapImage();\n    img.BeginInit();\n    img.UriSource = imageUri;\n    img.EndInit();\n    img.Freeze();\n    e.Result = img;\n}\n\nvoid _backgroundWorkerLoadImage_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)\n{\n    var img = e.Result as ImageSource;\n    imageControl.Source = img;\n}	0
9938428	9938363	Importing a lot interconnected data with EF	void Main()\n{\n    //Your list of objects\n    List<MyObject> TheListOfMyObjects=new List<MyObject>();\n\n    var dt=new DataTable();\n    dt.Columns.Add("Prop1",typeof(int));\n    dt.Columns.Add("Prop2",typeof(string));\n    foreach (var TheObject in TheListOfMyObjects)\n    {\n        dt.Rows.Add(TheObject.Prop1,TheObject.Prop2);\n    }\n    InsertWithBulk(dt,"YourConnnectionString","MyObject");\n}\nprivate void InsertWithBulk(DataTable dt,string connectionString,string tableName)\n{\n    using (SqlConnection destinationConnection =new SqlConnection(connectionString))\n    {\n        destinationConnection.Open();\n        using (SqlBulkCopy bulkCopy = new SqlBulkCopy(destinationConnection))\n        {\n            bulkCopy.DestinationTableName =tableName;\n\n            try\n            {\n                bulkCopy.WriteToServer(dt);\n            }\n            catch (Exception ex)\n            {\n                //Exception from the bulk copy\n            }\n        }\n    }\n}	0
23014010	23013671	How to enable Code First Entity Framework Migrations for Windows Azure when publishing from source control?	static MyContext()\n{\n    Database.SetInitializer(new MigrateDatabaseToLatestVersion<MyContext, Data.Migrations.Configuration>());\n}	0
24735904	24734316	How do I create and save file from stream on FTP folder directly?	FtpWebResponse response = (FtpWebResponse)requestFileUpload.GetResponse();\n\nStream myFTPStream = response.GetResponseStream();\n\n//copy data into stream\n\nresponse.Close();	0
32229747	32229580	Accessing an element inside a UserControl resource	public void Foo(){\n    var storyBoard = this.Resources["RotateImage"] as Storyboard;\n    // Get the storboard's value to get the DoubleAnimation and manipulate it.\n    var rotateImageAnimation = (DoubleAnimation)storyBoard.Children.FirstOrDefault();\n}	0
25508203	25508097	Inserting data on only first row	var cmd = new SqlCommand(con){\n CommandType = CommandType.StoredProcedure,\nCommandText = "prcfunddetails"\n};\n\n//add the needed parameters to the cmd without the values.\n//note: second parameter DbType SHOULD match type of the underlying db-field\ncmd.Parameters.Add("@action", SqlDbType.VarChar);\n.\n.\n.\n\ntextBox1.Text = "insert"; //I wonder what the effect of "delete" will be :-)\nfor (var i = 0; i<dataGridView1.Rows.Count; i++)\n{\n   //just place the correct values on the parameters\n   cmd.Parameters["@action"].Value = textBox1.Text;\n   cmd.Parameters["@fundid"].Value = dataGridView1.Rows[i].Cells[0].Value;\n   //etc//                 \n   cmd.ExecuteNonQuery();\n}\n//Messagebox out of the loop saves a sweet amount of mouseclicks\nMessageBox.Show("Records successfully");	0
1217839	1217711	How do I save an ArrayList to the application settings	Properties.Settings.Default.MySetting = myArrayList;	0
23916199	23900727	Xamarin IOS: How to display a popup control from button click	yourButton.TouchUpInside += (object sender, EventArgs e) => \n{\nYourControllerr yourController = new YourController();\n\nyourController.ModalPresentationStyle = UIModalPresentationStyle.FormSheet;\nthis.PresentViewController(yourController, true, null);\n};	0
6168000	6167903	Using data in a HTML.ActionLink inside a WebGrid.column, not possible?	grid.Column(columnName: "Date", format: (item) => Html.ActionLink(((string)item.Date), "Edit", new { id = item.id })),	0
27881100	27054565	Find Average of a node in Multiple JSON strings	double _avg1 = tmpEMP.Select(x => Convert.ToInt32(x.ElementAt(i).Rating)).Average();	0
11574405	11574376	Return list of specific property of object using linq	var list = stockItems.Select(item => item.StockID).ToList();	0
22939712	22939334	How to create EventHandler for dynamically created buttons (for each one) C# VS2010	void BTN_Click(object sender, EventArgs e)\n{\n    Button b = sender as Button;\n    if (b!=null)\n    {\n        //that's your button, with the properties created in the loop.\n    }\n}	0
31248644	31248470	Marking position in a C# list	public List<string> GetAllStringsStartingWith(char startsWith, List<string> allWords)\n    {\n        List<string> letterSpecificWords = allWords.FindAll(word => word.ToLower()[0].Equals(startsWith));\n        return letterSpecificWords;\n    }	0
8986422	8986133	Login failed for user 'devtestuser' - asp.net web app	Server=.;Initial Catalog=DATABASE_NAME;Integrated Security=False;User Id=sa;Password=;	0
5510789	5510763	C# - Passing the object type in a method parameter	public PageOf<TEntity> GetPageOfEntity<TEntity>(int pageNumber, int pageSize)\n    where TEntity : Entity\n{\n    Type entityType = typeof(TEntity);\n    ...\n}	0
14461895	14461709	Run random number with each assertion in a unit test	public static IEnumerable<object[]> Numbers\n    {\n        get\n        {\n            List<object[]> testCases = new List<object[]>();\n            Random random = new Random();\n            testCases.AddRange(\n                (from x in new[]\n                {1, 2, 3, 4, 5, 6, 7, 8}\n                select new object[] {x})\n                .OrderBy(x=>random.Next()));\n            return testCases;\n        }\n    }\n\n    [TestCaseSource("Numbers")]\n    public void CreateApplication(\n        int number\n        )\n    {\n         string company = DateTime.Now.ToString("dd/MM/yy ") + ("company") + number.ToString();\n\n    }	0
848425	848414	Running console application from C# but application can't create file	prog.StartInfo.WorkingDirectory = ...	0
19783784	19761620	Windows Store App Icon doesn't appear on Metro	pin to start	0
23389693	23388771	Looking for non-matched items in a collection via Linq	var items = new [] {\n    new { F1 = "ID1", F2 = "ID2", S = "AA", V = 15 },\n    new { F1 = "ID3", F2 = "ID2", S = "AA", V = 20 },\n    new { F1 = "ID1", F2 = "ID4", S = "AA", V = 25 },\n    new { F1 = "ID1", F2 = "ID4", S = "AA", V = 5  },\n    new { F1 = "ID1", F2 = "ID4", S = "AB", V = 5  },\n};\n\nvar f2s = items.Select(i => i.F2).Distinct();\n\nvar table =\n    from i in items\n    group i by new { i.F1, i.S } into g\n    select new \n    { \n        g.Key, \n        V = \n            from f in f2s\n            join x in g on f equals x.F2  into ps \n            from p in ps.DefaultIfEmpty()\n            select new { F = f, V = p != null ? p.V : 0 } into w\n            group w by w.F into h\n            select new { h.Key, V = h.Sum(c => c.V) }\n    };	0
31997065	31996930	Any c# programmers using Xamarin please	Add > New File > Empty Class	0
23148250	23148110	Send data file via email using C#	var smtp = new System.Net.Mail.SmtpClient();\n{\n    MailMessage mail = new MailMessage();\n    mail.From = new MailAddress(sFromEmail);\n    string sFrom = mail.From.ToString();\n\n    mail.Subject = sSubject;\n    mail.Body = sBody;\n    mail.IsBodyHtml = true;\n\n    Attachment sMailAttachment;\n    sMailAttachment = new Attachment("Your file file");\n    mail.Attachments.Add(sMailAttachment);\n\n    smtp.Host = "SMTPP HOST"\n    smtp.Port = "PORT" \n\n    smtp.DeliveryMethod = System.Net.Mail.SmtpDeliveryMethod.Network;\n    smtp.Credentials = new NetworkCredential(sSMTPUserName, sSMTPPassword);\n\n    smtp.Timeout = 30000;\n\n    smtp.Send(mail);  \n  }	0
21404441	21384871	Login SAP WebUI without opening browser	&sap-user=****&sap-password=***	0
10870032	10861504	Setting the value of insert parameter of SqlDataSource in codebehind	DateTime.Now.ToShortDateString();	0
23357370	23340539	ReportTelerik set data source programmatically	this.textBox1.Value="=Name";	0
1907204	1907195	How to Get IP Address?	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
2397181	2397170	get number of weeks away from today	(futureDate - DateTime.Today).TotalDays / 7	0
6833479	6833395	Any ideas on how to make the UI react when a property on a class is changed?	this.txtInvestor.DataBindings.Add("Text", this, "SelectedItem", false, DataSourceUpdateMode.OnPropertyChanged);	0
12414023	12413909	How do I get all items in a list that are inside of another list?	var items = listOfTest.SelectMany(lt => lt.myInnerObject).ToList();	0
10101884	10101821	how to refresh Captcha image in asp.net page	Image1.ImageUrl = "~/CImage.aspx?random=" + DateTime.Now.Ticks.ToString();	0
3801339	3801304	How to know redirect URL	WebRequest request = WebRequest.Create("http://migre.me/13rQa");\nvar response = request.GetResponse();	0
2994261	2993409	How to retrieve the GUID for Yahoo's Contacts API	URI:\n      http://social.yahooapis.com/v1/me/guid	0
2169516	2169255	Marshaling a struct while keeping it "unmanaged"	using System.Runtime.InteropServices;\n...\n  [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]\n  public struct Example {\n    [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 1024)]\n    public string name;\n    [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)]\n    int[] crop;\n  }	0
13037041	13036854	How to prevent modification of inherited properties?	public SmartComboBox()\n{\n    base.IsEditable = true;\n    base.IsTextSearchEnabled = false;\n    ...\n}\n\npublic new bool IsEditable { get { return base.IsEditable; } }\npublic new bool IsTextSearchEnabled { get { return base.IsTextSearchEnabled; } }	0
33940737	33939923	Is it possible to read correctly text file with wrong BOM in C#?	byte[] rawdata = File.ReadAllBytes("...");\nbyte[] correctedRawdata = rawdata.Skip(2).ToArray();\nEncoding encoder = Encoding.GetEncoding("iso-8859-9");\n\nstring text = encoder.GetString(correctedRawdata);	0
22900230	22897994	Update Listview with view model with button click	public ICommand UpdateScannersCommand\n{\n    get\n    {\n       return new RelayCommand(()=>\n{\n... update code here\n}\n}\n}	0
32739412	32739211	How to pass array to method	private void x()\n{\n    string sTestFile = "this is a test";   \n    string[] TestFileWords;\n\n    FixConcatString(sTestFile, out TestFileWords);\n}\n\n\nprivate void FixConcatString(string splayfile, **out** string[] sWordArray)\n{\n    char[] charSeparators = new char[] { '-' };\n    splayfile = splayfile.ToLower();\n    splayfile = splayfile.Replace(@"\", " ");\n\n    sWordArray =  splayfile.Split(charSeparators, StringSplitOptions.RemoveEmptyEntries);\n}	0
497842	497782	How to convert a string from utf8 to ASCII (single byte) in c#?	using System.Text;\n\nstring inputString = GetInput();\nvar encoder = ASCIIEncoding.GetEncoder();\nencoder.Fallback = new EncoderReplacementFallback(string.Empty);\n\nbyte[] bAsciiString = encoder.GetBytes(inputString);\n\n// Do something with bytes...\n// can write to a file as is\nFile.WriteAllBytes(FILE_NAME, bAsciiString);\n// or turn back into a "clean" string\nstring cleanString = ASCIIEncoding.GetString(bAsciiString); \n// since the offending bytes have been removed, can use default encoding as well\nAssert.AreEqual(cleanString, Default.GetString(bAsciiString));	0
8654890	8652890	How do I compress and encrypt a string to another string?	.ToArray()	0
19346006	19345988	Convert a list of strings to a single string	string Something = string.Join(",", MyList);	0
18945358	18672102	How to write into an existing textfile in windows phone?	public static void WriteBackgroundSetting(string currentBackground)\n    {\n        const string fileName = "RecipeHub.txt";\n        using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())\n        {\n            if(myIsolatedStorage.FileExists(fileName))\n                myIsolatedStorage.DeleteFile(fileName);\n            var stream = myIsolatedStorage.CreateFile(fileName);\n            using (StreamWriter isoStream = new StreamWriter(stream))\n            {\n                isoStream.WriteLine(currentBackground);\n            }\n        }\n\n    }	0
31563283	31562993	Add class members and data members of constructor to a list in c#	private List<X> Method(string result)\n    {\n        List<X> ret = new List<X>();\n        X temp = new X\n        {\n            Comments = new List<Y>\n            {\n                new Y() { Author = "Author", Body = "Body" }\n            },\n            Key = "issueKey"\n        };\n\n        ret.Add(temp);\n        return ret;\n    }	0
21733131	21732517	How to check in a linq query for null?	var departmentId = booking.Item.DepartmentId;\nvar users = from s in db.Users\nwhere s.DepartmentId == departmentId && s.UserEmail != null\nselect s;	0
20146983	20145834	add DIV around every asp:DropDownList control code behind	protected override void OnPreInit(EventArgs e)\n{\nbase.OnPreInit(e);\n\nvar j = 0;\nforeach (DropDownList control in form1.Controls.OfType<DropDownList>().ToList())\n{\n    var div = new HtmlGenericControl();\n    div.ID = "div" + j;\n    div.TagName = "div";\n    div.Attributes["class"] = "myClass";\n    div.Controls.Add(control); // or control.Controls.Add(div); but this wouldn't wrap it.\n    j++;\n\n    form1.Controls.Add(div);\n}	0
5774271	5774224	How to change the SelectMethod of ObjectDataSource programatically?	GetProjectsDataSource.SelectMethod = "GetProjectByUsernameDeptCd";\n Parameter p1 = new Parameter("parameter1 ",TypeCode.String);\n Parameter p2 = new Parameter("parameter2 ",TypeCode.String);\n GetProjectsDataSource.SelectParameters.Add(p1);\n GetProjectsDataSource.SelectParameters.Add(p2);	0
6368952	6368931	NHibernate : QueryOver in generic method	public IList<T> List<T>() where T : class, IAdminDecimal	0
20361722	20361678	C# Set String To Current Date +1	if (dayofweektext.Contains("tomorrow"))\n{\n    dayofweektext = DateTime.Today.AddDays(1).DayOfWeek.ToString();\n}	0
948658	947973	How do I dynamically create new Hyperlinks in ASP.NET?	HyperLink hyp = new HyperLink();\n    hyp.ID = "hypABD";\n    hyp.NavigateUrl = "";\n    Page.Controls.Add(hyp);	0
5085205	5084910	Locally Hosted WCF service - I don't want clients to have to authenticate	host.AddServiceEndpoint(\n            typeof(ISMService),\n            new NetTcpBinding(SecurityMode.None),\n            "");	0
10322101	10316656	How to create an async/background process within a WCF operation?	// Log something going on.\nSystem.Threading.ThreadPool.QueueUserWorkItem((args) =>\n{\n   System.Diagnostics.EventLog.WriteEntry("my source", "my logging message");\n});	0
5090542	5090396	Access wrapped object	interface IWrappedEntity<T>\n{\n    T GetWrappedEntity();\n}	0
11469695	11469084	Evenly distribute collection into new Arrays	const double bucketSize = 15.0;\nvar totalItems = (double)linjer;\nvar optimumBuckets = Math.Ceiling(totalItems / bucketSize);\nvar itemsPerBucket = (int)Math.Ceiling(totalItems / optimumBuckets);\n\nvar buckets = new int[(int)optimumBuckets];\n\nvar itemsLeft = (int)totalItems\nfor (var i = 0; i < buckets.length; i++)\n{\n    if (itemsLeft < itemsPerBucket)\n    {\n        buckets[i] = itemsLeft;\n    }\n    else\n    {\n        buckets[i] = itemsPerBucket;\n    }\n    itemsLeft -= itemsPerBucket;\n}	0
16211363	16210004	Shell Context Menus	xmlns:asmv1="urn:schemas-microsoft-com:asm.v1"\n  xmlns:asmv2="urn:schemas-microsoft-com:asm.v2"\n  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n  <assemblyIdentity version="1.0.0.0" name="MyApplication.app" />\n  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v2">\n    <security>\n      <requestedPrivileges xmlns="urn:schemas-microsoft-com:asm.v3">\n        <requestedExecutionLevel level="requireAdministrator"\n      uiAccess="false" />\n      </requestedPrivileges>\n    </security>\n  </trustInfo>\n</asmv1:assembly>	0
20285083	20284573	JSON format is not supported by highchart	var d = [{"x":"58770"},{"x":"79035"},{"x":"84030"},{"x":"90145"},{"x":"95630"},{"x":"102580"},{"x":"108950"},{"x":"113615"},{"x":"118765"},{"x":"124055"}],\n    dLen = d.length,\n    ret = [];\n\nfor(var i = 0; i < dLen; i++) { \n    ret.push( parseInt(d[i].x, 10));\n}\n\n// ret contains: [58770, 79035, 84030, 90145, 95630, 102580, 108950, 113615, 118765, 124055]	0
11722911	11721024	Clear table in a specific time and only once (every day)	sSrcUrl = "http://www.this-page-intentionally-left-blank.org/"\nsDestFolder = "C:\"\nsImageFile = "filename.txt"\nset oHTTP = WScript.CreateObject("MSXML2.ServerXMLHTTP")\noHTTP.open "GET", sSrcUrl, False\noHTTP.send ""\nset oStream = createobject("adodb.stream")\nConst adTypeBinary = 1\nConst adSaveCreateOverWrite = 2\noStream.type = adTypeBinary\noStream.open\noStream.write oHTTP.responseBody\noStream.savetofile sDestFolder & sImageFile, adSaveCreateOverWrite\nset oStream = nothing\nset oHTTP = nothing\nWScript.Echo "Done..."	0
30727411	30727153	Want to be able to change password using variable	String PassWord;\nPassWord = "PASSWORD";\nif (textBox1.Text == PassWord)	0
1165378	1165321	Change the Access Modifiers of ASP.NET controls	/// To modify move field declaration from designer file to code-behind file.	0
14814144	14814056	Compare string with slashes	string a = @"C:\xxx\1.png";\nstring b = @"C:\xxx\1.png";\n\nbool blnEqule = a == b;	0
20307524	20307488	How show image from a data base into a picturebox, C# and Sql Server	private void button1_Click(object sender, EventArgs e)\n{\n    Image tempImage;\n    using (var conn = new SqlConnection("myconnectionstring"))\n    {\n        conn.Open();\n        using (\n            var cmd = new SqlCommand("SprocToGetImageBytes", conn) {CommandType = CommandType.StoredProcedure})\n        {\n            using (var rdr = cmd.ExecuteReader())\n            {\n                var buffer = (byte[])rdr[0];\n                using (var ms = new MemoryStream(buffer))\n                {\n                    tempImage = Image.FromStream(ms); //theres your image.\n                    pictureBox1.Image = tempImage;\n                    pictureBox1.Refresh();\n                }\n            }\n        }\n    }\n}	0
1522253	756455	Programmatically derived Columns from flatfile source using SSIS DataFlowTask	InstanceDestination.SetComponentProperty("OpenRowset", \nDestinationTableNameInternal);        \n\nInstanceDestination.SetComponentProperty("AccessMode", 0);	0
7208206	7208037	Format time in DataGridView to local timezone	private void OnCellFormatting(object sender, DataGridViewCellFormattingEventArgs e)\n    {\n        if (e.RowIndex < 0 || e.ColumnIndex < 0) return;\n        DataGridView dgView = (DataGridView)(sender);\n        // no need to add TaskTime...\n        if (e.ColumnIndex != dgView.Columns["TaskDate"].Index) return;\n        string cellValue = e.Value + " " + dgView.CurrentRow.Cells[dgView.Columns["TaskTime"].Value);\n        DateTime dtValue;\n        DateTime.TryParse(cellValue, out dtValue);\n        DateTime dtValueUTC = TimezoneInfo.ConvertTimeToUtc(dtValue, "Eastern Time Zone");\n        e.Value = dtValueUTC.Value.ToLocalTime();\n    }	0
22907216	22907101	Cannot convert a decimal value to money, C# -> SP SQL Server	command.Parameters.Add(\n    new SqlParameter("@ResidualValue", SqlDbType.Money).Value = importExportOptions.ResidualValue;	0
14469505	14467241	Capture VS local variables while debugging in EnvDTE	DTE dte = (DTE).Package.GetGlobalService(typeof(DTE));\nif(dte.Debugger.CurrentStackFrame != null) // Ensure that debugger is running\n{\n    EnvDTE.Expressions locals = dte.Debugger.CurrentStackFrame.Locals;\n    foreach(EnvDTE.Expression local in locals)\n    {\n        EnvDTE.Expressions members = expression.DataMembers;\n        // Do this section recursively, looking down in each expression for \n        // the next set of data members. This will build the tree.\n        // DataMembers is never null, instead just iterating over a 0-length list.\n    }\n}	0
1724041	1724025	In C#, what's the best way to store a group of constants that my program uses?	public static class Constants\n{\n   public static string SomeConstant { get { return "Some value"; } }\n}	0
3499462	3499425	Correct approach to handle data verification	Employee emp = EmployeeRepository.GetById("E11234");\nif (emp.IsValid())\n{ \n   do whatever is required \n}\nelse {     \n  // show an error message\n}	0
24152198	24151644	How to change a for loop to a foreach, while iterating through DataGridView control values?	foreach (DataGridViewRow row in this.DB.Rows)\n{\n    // Add this to break the loop when row is last blank row\n    if (row.IsNewRow)\n        break;\n\n    foreach (DataGridViewCell cell in row.Cells)\n    {\n        if (cell.Value != null)\n            filewrite.Write(cell.Value.ToString() + " ");\n    }\n    file.WriteLine();\n}	0
5405481	5405237	How to get attachment of EmailMessage?	string sType = item.Attachments[i].ContentType.ToLower();	0
28825509	28825379	Does not contain a definition for 'RootVisual' in Windows Phone 8.1	(Windows.UI.Xaml.Window.Current.Content as Frame).Navigate(typeof(FeedBackMessageBox),args);	0
15248019	15247850	How to delete a particular value from a datatable in c#	//Get the row that is selected\nDataGridViewRow dr = selectedRows.Cast<DataGridViewRow>().FirstOrDefault();\n//Your temp DataTable\nDataTable dtTemp = new DataTable();\n//If there is a row selected\nif (dr != null)\n{\n  var rowToRemove = dtTemp.Rows.Cast<DataRow>().FirstOrDefault(row => row[0] == dr.Cells[0].Value);\n  if (rowToRemove != null)\n    dtTemp.Rows.Remove(rowToRemove);\n}	0
28724127	28723009	MediaElement doesn't play files from internal memory of device	private async void List_OnItemClick(object sender, ItemClickEventArgs e)\n{\n    var item = (ItemViewModel) e.ClickedItem;\n    var stream = await item.File.OpenAsync(FileAccessMode.Read);        \n    Media.SetSource(stream, item.File.ContentType);\n}	0
6264654	6261167	Prepared statement vs. Stored Procedure with RefCursor	command.Prepare()	0
34058632	34058359	how to replace only certain certain digits in a pattern coming in a file	SortedDictionary<string, string> Dates = new SortedDictionary<string, string>();\nDates.Add("1", "10/06/2015WD 2  ");\nDates.Add("2", "10/07/2015HD 1");\nDates.Add("3", "10/08/2015WD 2 ");\nfor(int i = 0; i < Dates.Count; i++)\n {\n   string Key = Dates.ElementAt(i).Key;\n   string CurrentValue = Dates.ElementAt(i).Value.Trim();\n   string CurrentValueLastChar = CurrentValue.Substring(CurrentValue.Length - 1, 1);\n   if (i - 1 != -1 && i + 1 < Dates.Count)\n    {\n      string PreviousValue = Dates.ElementAt(i - 1).Value.Trim();\n      string NextValue = Dates.ElementAt(i + 1).Value.Trim();\n      string PreviousValueLastChar = PreviousValue.Substring(PreviousValue.Length - 1, 1);\n      string NextValueLastChar = NextValue.Substring(NextValue.Length - 1, 1);\n      if (PreviousValueLastChar == NextValueLastChar)\n           Dates[Key] = (Dates[Key].Remove(Dates[Key].Length - 1)) + PreviousValueLastChar;\n\n    }                \n\n }	0
19893931	19893501	Ambiguity between settings in C#	Settings1.Default.Value1 = "11";\nSettings1.Default.Save();\n\nSettings2.Default.Value1 = "22";\nSettings2.Default.Save();	0
7359396	7359347	Load XML in MVC Controller	if(File.Exists(yourFilePathHere))	0
11363068	11340057	RESTful partial request & partial serialization	[DataContract]\n   public class Unicorn {   \n\n    [DataMember (EmitDefaultValue=false)] \n    public string Id { get; set; }     \n\n    [DataMember (EmitDefaultValue=false)] \n    public string Color { get; set; }     \n\n    [DataMember (EmitDefaultValue=false)] \n    public int? Size { get; set; }     \n\n    [DataMember (EmitDefaultValue=false)] \n    public DateTime? BirthDate { get; set; } \n}	0
7926501	7926437	inheriting from a Forms.Timer	public static class TimerExtensions\n {\n     public static MyTimerExtension(this Timer timer)\n     {\n         // use timer here just as any method parameter\n     }\n }\n\n //usage\n\n timer1.MyTimerExtension();	0
17889943	17889900	Modifying the parent datarow in a Silverlight DataGrid	checkBox.DataContext	0
21671757	21671073	Obtaining the length of Coresponding Colors in each row of Image	for (int i = 0; i < image.rows; i++)\n{\n    for(int j=0; j< image.cols; j++)\n    {   \n        int b = image.at<cv::Vec3b>(i,j)[0];\n        int g = image.at<cv::Vec3b>(i,j)[1];\n        int r = image.at<cv::Vec3b>(i,j)[2];\n    }\n// add your comparison here. Dun wanna do your work for u.\n}	0
31364081	31359586	C#: Change Object from MainWindow in an Dialog using Gtk	var md = new MessageDialog (\n            null,\n            DialogFlags.DestroyWithParent,\n            MessageType.Info,\n            ButtonsType.OkCancel,\n            "Your message");\n\nmd.Response += (o, args) => {\n    if (args.ResponseId == ResponseType.Ok) {\n        // do your stuff with the object\n    }\n};\n\nmd.Run ();\nmd.Destroy ();	0
29081962	29081826	Datatype.Date how to set minimum date to Today?	public sealed class PresentOrFutureDateAttribute: ValidationAttribute\n        {\n            protected override ValidationResult IsValid(object value, ValidationContext validationContext)\n            {                 \n                // your validation logic\n                if (Convert.ToDateTime(value) >= DateTime.Today)\n                {\n                    return ValidationResult.Success;\n                }\n                else\n                {\n                    return new ValidationResult("Past date not allowed.");\n                }\n            }\n        }	0
476504	476499	Naming conventions in C# compared to Java	CompanyName.ProductName\nCompanyName.ProductName.ClassName\nCompanyName.ClassName.IsUpperCase(string str)	0
8272209	8272148	Is it possible to create an array from the frequency of chars within a string?	input.GroupBy(x => x).OrderByDescending(x => x.Count()).Select(x => x.Key).ToArray();	0
1499360	1499332	How to invoke method, using reflection, on instantiated object?	PropertyInfo piInstance = typeof(IGWUIElement).GetProperty("property_name");\npiInstance.SetValue(newUIElement, value, null);	0
29181280	29175237	using a converter while reading xaml from string using XamlReader.Parse()	public class DateConverter : IValueConverter\n{\n    ...\n}	0
19732157	19717355	Execute Select with more than one column and assign to Labels	string sqlCom = String.Format(@"SELECT [Version],version2 FROM ConfigSystem");\n        SqlConnectionStringBuilder ConnectionString = new SqlConnectionStringBuilder();\n        ConnectionString.DataSource = SQL06;\n        ConnectionString.InitialCatalog = "SuperSweetdb";\n        ConnectionString.IntegratedSecurity = true;\n\n        SqlConnection cnn = new SqlConnection(ConnectionString.ToString());\n\n        using (var version = new SqlCommand(sqlCom, cnn))\n        {           \n            cnn.Open();\n\n            using(IDataReader dataReader = version.ExecuteReader()) \n            {\n                while (dataReader.Read())\n                {\n                    label7.Text = dataReader["Version"].ToString();\n                    label9.Text = dataReader["VertexDataVersion"].ToString();\n                }\n            }\n\n        };	0
13642482	13642401	Windows Phone 8 Http request with custom header	request.Headers["mycustomheader"] = "abc";	0
19971417	19971346	How can i return more than one results from a single stored procedure?	using (SqlConnection conn = new SqlConnection(connection))\n{\n    DataSet dataset = new DataSet();\n    SqlDataAdapter adapter = new SqlDataAdapter();\n    adapter.SelectCommand = new SqlCommand("YourStoredProcedure", conn);\n    adapter.SelectCommand.CommandType = CommandType.StoredProcedure;\n    adapter.Fill(dataset);\n    return dataset;\n}	0
9335217	9334963	Show a Form behind everything else, and without stealing focus?	public static class HWND {\n  public static readonly IntPtr\n  NOTOPMOST = new IntPtr(-2),\n  BROADCAST = new IntPtr(0xffff),\n  TOPMOST = new IntPtr(-1),\n  TOP = new IntPtr(0),\n  BOTTOM = new IntPtr(1);\n}\n\npublic static class SWP {\n  public static readonly int\n  NOSIZE = 0x0001,\n  NOMOVE = 0x0002,\n  NOZORDER = 0x0004,\n  NOREDRAW = 0x0008,\n  NOACTIVATE = 0x0010,\n  DRAWFRAME = 0x0020,\n  FRAMECHANGED = 0x0020,\n  SHOWWINDOW = 0x0040,\n  HIDEWINDOW = 0x0080,\n  NOCOPYBITS = 0x0100,\n  NOOWNERZORDER = 0x0200,\n  NOREPOSITION = 0x0200,\n  NOSENDCHANGING = 0x0400,\n  DEFERERASE = 0x2000,\n  ASYNCWINDOWPOS = 0x4000;\n}\n\n[DllImport("user32.dll")]\npublic static extern bool SetWindowPos(IntPtr hWnd, IntPtr hWndInsertAfter, int X, int Y, int cx, int cy, int uFlags);\n\nprivate void button1_Click(object sender, EventArgs e) {\n  RunnerForm frm = new RunnerForm();\n  SetWindowPos(frm.Handle, HWND.BOTTOM, 0, 0, 0, 0, SWP.SHOWWINDOW | SWP.NOMOVE | SWP.NOOWNERZORDER | SWP.NOSIZE | SWP.NOACTIVATE);\n}	0
17684061	17683691	How to get this captcha image link?	Cookie: ASPSESSIONIDASDCDQBE=IOMFMDMCOBNECLCLEAIFJPEK; ASPSESSIONIDASCDBRAD=AAEFMDMCKLOAMDIAJPGNNNDG\n\nCookie: ASPSESSIONIDASDCDQBE=IOMFMDMCOBNECLCLEAIFJPEL; ASPSESSIONIDASCDBRAD=AAEFMDMCKLOAMDIAJPGNNNDH	0
22816858	22816614	Mobile application development in Visual Studio 2012 Ultimate	Templates -> Visual C# -> Windows Phone	0
20855420	20837721	How do I update a specific portion of a bitmap image?	// clear the tile to be redrawn\nint x2 = xToUpdate * Program.pixelSize;\nint y2 = yToUpdate * Program.pixelSize;\n\nfor (int a = x2; a <= x2 + Program.pixelSize - 1; a++)\n{\n    for (int b = y2; b <= y2 + Program.pixelSize - 1; b++)\n    {\n        mapBitmapFringe.SetPixel(a, b, Color.Transparent);\n    }\n }	0
25149456	25149391	Removing element value of the following element	var passwords = document.XPathSelectElements("//key[text()='Password']/following-sibling::string[1]");\nforeach(XNode elem in passwords)\n{\n  elem.SetValue(string.Empty);\n}	0
4088879	4088842	c# display table from sql server on winform	using(var connection = new SqlConnection(myConnectionString))\nusing(var adapter = new SqlDataAdapter(mySelectQuery, connection))\n{\n   var table = new DataTable();\n   adapter.Fill(table);\n   this.dataGridView.DataSource = table;\n}	0
34456447	34442961	Overriding OnKeyDown in custom control puts character in start	e.Handled = e.SuppressKeyPress = true;	0
15535770	15535750	Find a char in a List of Strings	listOfStrings.Where(s => s.Contains('?'));	0
11056909	11056593	Optimizer, how one method can know how many parameters are in another	public class A\n{\n    public void MyMethod(int integer, string str)\n    {\n    }\n}\n\nvoid Main()\n{\n    System.Reflection.MethodInfo method = typeof(A).GetMethod("MyMethod");\n    ParameterInfo[] pars = method.GetParameters();\n    foreach (ParameterInfo p in pars) \n    {\n        Console.WriteLine(p.Name + ": " + p.ParameterType);\n    }\n}	0
32047484	32047064	How to throttle multiple asynchronous tasks?	static void RunThreads(int totalThreads, int throttle) \n{\n    Observable\n        .Range(0, totalThreads)\n        .Select(n => Observable.FromAsync(() => DoSomething(n)))\n        .Merge(throttle)\n        .Wait();\n}	0
9712786	9712699	read website information, display application	private void Form1_Load(object sender, EventArgs e)\n{\n    webBrowser1.Navigated += new WebBrowserNavigatedEventHandler(webBrowser1_Navigated);\n    webBrowser1.Navigate("http://stackoverflow.com/questions/9712699/read-website-information-display-application");    \n}\n\n\nprivate void webBrowser1_Navigated(object sender, WebBrowserNavigatedEventArgs e)\n{\n\n    foreach (HtmlElement ele in webBrowser1.Document.GetElementsByTagName("SPAN"))\n    {\n        if (ele.GetAttribute("title") == "reputation score")\n        {  \n            MessageBox.Show(ele.Parent.Children[0].InnerText + " - "+ ele.InnerHtml);\n        }\n    }\n}	0
2161118	2152985	Windows Mobile content encryption	private Byte[] CryptoKey\n{\n    get { return new Byte[] { 0x0E, 0x41, 0x6A, 0x29, 0x94, 0x12, 0xEB, 0x63 }; }\n}\n\npublic Byte[] Encrypt(Byte[] bytes)\n{\n    using (var crypto = new DESCryptoServiceProvider())\n    {\n        var key = CryptoKey;\n\n        using (var encryptor = crypto.CreateEncryptor(key, key))\n        {\n            return encryptor.TransformFinalBlock(bytes, 0, bytes.Length);\n        }\n    }\n}\n\npublic Byte[] Decrypt(Byte[] bytes)\n{\n    using (var crypto = new DESCryptoServiceProvider())\n    {\n        var key = CryptoKey;\n\n        using (var decryptor = crypto.CreateDecryptor(key, key))\n        {\n            return decryptor.TransformFinalBlock(bytes, 0, bytes.Length);\n        }\n    }\n}	0
5348996	5348954	Checkbox in datagrid view in Window form in C#	foreach (DataGridViewRow var in dataGridView1.Rows)\n{\n    var.Cells[3].Value = true;\n}	0
10058036	10057939	Resharper formatting for single-line if statement	if(tired)\n    Sleep();\nelse\n    Party()	0
27449124	23750220	How to make line chart start from 0 X-Axis	chart1.ChartAreas[0].AxisX.IsMarginVisible = false;	0
21839192	21805066	Writing a library that is dependency-injection "enabled"	[Injection]	0
18373169	18372995	Export sql data to xml	DataSet ds = new DataSet("ITEMS");	0
26312816	26311968	how to negate a RegEx match using Data annotations in asp.net mvc?	^(?!.*?(https?://)?([\da-z.-]+)\.([a-z.]{2,6})([/\w .-]*)*/?).*$	0
5073537	5069343	MongoDB C# official driver : Maping objects to short names to limit space	public class SomeClass\n{\n    public BsonObjectId Id { get; set; }\n\n    [BsonElement("dt")]\n    public DateTime SomeReallyLongDateTimePropertyName { get; set; }\n}	0
17976800	17976726	variable scope inside try catch block	StreamReader myReader = null;	0
26314802	26314604	Getting rid of black background when using a render target	GraphicsDevice.Clear(Color.TransparentBlack);	0
8569750	8569727	How to implement this struct as a class without pointers in c#?	class Reference<T>\n{\n    public T Value {get; set;}\n}	0
22734239	22734029	Routing to different default action for different controllers	routes.MapRoute(\n  name: "Uno",\n  url: "Uno/{action}/{id}",\n  defaults: new { controller = "Uno", action = "IndexHoopls", id = "17" }\nroutes.MapRoute(\n  name: "Default",\n  url: "{controller}/{action}/{id}",\n  defaults: new { controller = "Home", action = "Index", id = "17" }	0
699616	699580	C# AssemblyFileVersion usage within a program	public static string Version\n    {\n        get\n        {\n            Assembly asm = Assembly.GetExecutingAssembly();\n            FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location);\n            return String.Format("{0}.{1}", fvi.ProductMajorPart, fvi.ProductMinorPart);\n        }\n    }	0
2403809	2403767	String.Format Phone Numbers with Extension	//[snip]\nelse if (phoneDigits.ToString().Length > 10)\n        {\n            return String.Format("{0:(###) ###-#### x}{1}", phoneDigits.Substring(0,10), phoneDigits.Substring(10) );\n        }\n//[snip]	0
14017637	14016536	RichTextBox to BackgroundWorker	private void button1_Click(object sender, EventArgs e)\n    {\n        backgroundWorker1.RunWorkerAsync(richTextBox1.Text);\n\n    }\n\n    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)\n    {\n        string text = (string)e.Argument;\n        MessageBox.Show(text);\n\n    }	0
16083273	16079217	How to generate and auto increment Id with Entity Framework	public int Id { get; set; }	0
16113343	16113299	Instantiate multiple classes from a single generic overide style class	public clas MyClass1 : IClassProcessor	0
5581339	5581140	In C# how do I get the list of local computer names like what one gets viewing the Network in windows explorer	var root = new DirectoryEntry("WinNT:");\nforeach (var dom in root.Children) {\n    foreach (var entry in dom.Children) {\n        if (entry.Name != "Schema") {\n            Console.WriteLine(entry.Name);\n        }\n    }\n}	0
11513178	11513075	Add a title when exporting gridview data to a doc file	GridView1.Caption = "StackOverFlow Grid...";	0
16811452	16811368	How to make if statment inside linq	References = (g.SelectMany(entry => entry.References).Count() == 0)\n   ? g.SelectMany(entry => entry.References).OrderBy(t => t).ToList() : null;	0
8179664	8174534	How to map dictionary with entity as key and class with corresponding user type as value?	mapping.HasMany(x => x.PropName)\n    .Table("Linktable")\n    .AsEntityMap("SomeOtherEntity_id")\n    .Element("PcmStream_id", e => e.Type<MyUserType>());	0
28588762	28588695	Regex replace all matched tokens with lowercase	var output = Regex.Replace(input, @"\$\$.+?\$\$", m => m.Value.ToLower());	0
9301470	9300985	Saving Collections in WP7 with isolatedstorage	public class TournamentMain\n{\n    public int ID { get; set; }\n    public string name { get; set; }\n    public double buy_in { get; set; }\n    public double re_buy { get; set; }\n    public double add_on { get; set; }\n    public int blindindex { get; set; }\n    public int placeindex { get; set; }\n    public int playerindex { get; set; }\n    public ObservableCollection<Blind> blinds { get; set; }\n    public ObservableCollection<Player> players { get; set; }\n    public ObservableCollection<Place> places { get; set; }\n    public ObservableCollection<Paidplace> paidplaces {get; set;} \n\n    public TournamentMain() \n    {\n        ID = 0;\n        blindindex = 1;\n        placeindex = 1;\n        playerindex = 1;\n        players = new ObservableCollection<Player>();\n        places = new ObservableCollection<Place>();\n        blinds = new ObservableCollection<Blind>();\n        paidplaces = new ObservableCollection<Paidplace>();\n   }	0
6400664	6400382	How do I extract values from controls and write it on XML?	foreach(Control control in this.Controls)\n{\n    //here 'this' is representing the form you want to iterate through\n\n    //you can check whether it is a combobox or a text box\n    if(control.GetType() == typeof(Combobox))\n    {\n        //this is a combo box\n    }\n    else if(control.GetType() == typeof(Textbox))\n    {\n        //this is a text box\n    }\n}	0
16998106	2910471	Querying a Single Column with LINQ	public static List<TResult> GetSingleColumn<T, TResult>(\n   Expression<Func<T, bool>> predicate,\n   Expression<Func<T, TResult>> select) where T : class\n  {\n   using (var db = GetData())\n   {\n    var q = db.GetTable<T>().AsQueryable();\n    if (predicate != null)\n     q = q.Where(predicate).AsQueryable();\n    var q2 = q.Select(select);\n    return q2.ToList();\n   }\n  }	0
31459989	31455296	Insert information from view into another table without user input	SqlCommand command = new SqlCommand("yourStoredProcedureName", conn);\ncommand.ExecuteNonQuery();\n...	0
25557343	25557262	How to create a "typedef to a function pointer" in C#?	{\n    bool AFunction(ref int x, params object[] list)\n    {\n        /* Some Body */\n    }\n\n    public delegate bool Proc(ref int x, params object[] list);  // Declare the type of the "function pointer" (in C terms)\n\n    public Proc my_proc;  // Actually make a reference to a function.\n\n    my_proc = AFunction;         // Assign my_proc to reference your function.\n    my_proc(ref index, a, b, c); // Actually call it.\n}	0
21856329	21855971	Minimize my winform application into system tray	private void MainForm_Resize(object sender, EventArgs e)\n    {\n        switch (this.WindowState)\n        {\n            case FormWindowState.Maximized:\n                this.ShowInTaskbar = true;\n                break;\n            case FormWindowState.Minimized:\n                this.ShowInTaskbar = false;\n                break;\n            case FormWindowState.Normal:\n                this.ShowInTaskbar = true;\n                break;\n            default:\n                break;\n        }\n    }	0
22240385	22240167	Get Max and Min in a single LINQ query	objects.Aggregate(\n    new {\n        MinA = int.MaxValue,\n        MaxB = string.Empty\n    },\n    (accumulator, o) => new {\n        MinA = Math.Min(o.A, accumulator.MinA),\n        MaxB = o.B > accumulator.MaxB ? o.B : accumulator.MaxB\n    });	0
9787137	9787090	storing a byte array in web.config	string value = ... // value from config file.\nbyte[] key = value.Split(new[] {','}).Select(s => Convert.ToByte(s, 16))\n                                     .ToArray();	0
25802275	25802195	C#: access variable in the inner scope from the outer scope	public class Project{\n    public string id{get;set;} \n    public string wetterdatei{get;set;}\n    public string fruchtfolge {get;set;} \n    public string bodenprofil {get;set;} \n}\n\n\npublic static Project leseProjektDatei(){\nProject projekt = new Project();\nwhile ((zeile = datei.ReadLine()) != null)\n       {\n           projekt.id = zeile.Substring(0, 5);\n           projekt.wetterdatei = zeile.Substring(7, 14);\n           projekt.fruchtfolge = zeile.Substring(22, 14);\n           projekt.bodenprofil = zeile.Substring(37, 14);\n\n             } \nreturn projekt;\n}	0
13111324	13111246	set focus from class library	namespace ClassLibrary\n{\n    public class Utility\n    {\n        public static string ReadData()\n        {\n            return "abc";\n        }\n    }\n}\n\nnamespace Win_App\n{\n    public partial class Form1 : Form\n    {\n       private void button2_Click(object sender, EventArgs e)\n       {\n            if (ClassLibrary.Utility.ReadData() == null)\n            {\n                MessageBox.Show("error, redo");\n                button2.Focus(); //you should handle this here.\n                return;\n            }\n        }\n    }\n}	0
1768041	1768023	How to use "\" in a string without making it an escape sequence - C#?	//Initialize with a regular string literal.\nstring oldPath = "c:\\Program Files\\Microsoft Visual Studio 8.0";\n\n// Initialize with a verbatim string literal.\nstring newPath = @"c:\Program Files\Microsoft Visual Studio 9.0";\n                 ???	0
21493854	21493627	Windows Service application with a GUI frontend	Public Sub New()\n        Dim spi As ServiceProcessInstaller = New ServiceProcessInstaller\n    Dim si As ServiceInstaller = new ServiceInstaller\n\n    spi.Account = ServiceAccount.LocalSystem\n\n        si.StartType = ServiceStartMode.Manual\n        si.ServiceName = "Service1"\n\n        Installers.Add(si)\n        Installers.Add(spi)\n\n    End Sub	0
25729805	25728091	Serialize a array of lists	TextWriter textWriter = new StreamWriter(@"Serialized.xml");\n        XmlSerializer serializer = new XmlSerializer(_pointList[0].GetType());\n        for (int i = 0; i < ListSize; i++)\n        {                \n            serializer.Serialize(textWriter, _pointList[i]);\n        }	0
18544048	18543791	How do I used a database I created in MS SQL Server 2008 R2 with a VS C# Project?	using (var connection = new SqlConnection(connectionString))\n        using (var command = new SqlCommand(queryString, connection))\n        {\n            command.Connection.Open();\n            command.ExecuteNonQuery();\n        }	0
33824605	33824508	Get the folder of a file.	FileInfo f = new FileInfo(@"C:\Users\Ryan\Documents\myImage.jpg");\nstring result = Path.Combine(f.Directory.Name, f.Name);	0
33201406	33201319	Calculate the five corners of a star - method doesn't work correctly	for (int i = 1; i < 5; i++)\n{\n    double[] newVector = RotateVector2d(points[i - 1, 0], points[i - 1, 1], 2.0*Math.PI/5);   // degrees in rad !\n    points[i, 0] = newVector[0];\n    points[i, 1] = newVector[1];\n    Debug.WriteLine(newVector[0] + " " + newVector[1]);\n}	0
27633268	27633162	Send an instance from a class is same as send it by reference	void Main()\n{\n   Student student = new Student();\n   FillStudentUnformation(student);\n   Console.WriteLine(student.Name); // Here you will not get name\n   FillStudentUnformationRef(ref student);\n   Console.WriteLine(student.Name);    // you will see name you have set inside method.\n}\n\nvodi FillStudentUnformation(Student student)\n{\n   //If here if you do \n   student = new Student(); \n   student.Name = "test"; // This will not reflect outside.\n}\n\nvodi FillStudentUnformationRef(ref Student student)\n{\n   //If here if you do \n   student = new Student(); \n   student.Name = "test ref"; // This will not reflect outside.\n}	0
9944651	9944587	Convert a float to a byte[] in order to send through a named pipe (C++)	const void *data = &myFloat;\nsize_t size = sizeof myFloat;	0
26677725	26677399	How to close all defined childform with C#	foreach (Form frm in this.MdiChildren)\n{\n        if (frm.GetType() == typeof(Can_ListCandidate))\n        {\n            frm.Dispose();\n            //return;\n        }\n}	0
6185351	6185299	c#. Parse and find some word in string	var input = "bla bla bla bla  <I NEED THIS TEXT> ";\n\nvar match = Regex.Match(input, @".*?<(?<MyGroup>.*?)>");\nif (match.Success)\n    var text = match.Groups["MyGroup"].Value;	0
13644034	13642204	Update a canvas children from a saved txt file	parentWindow.grid.Children.Remove(parentWindow.canvas);\n            parentWindow.canvas = (Canvas)System.Windows.Markup.XamlReader.Load(xmlReader);\n            parentWindow.grid.Children.Add(parentWindow.canvas);	0
6074891	6074481	How set the value of a Label?	messagelb.Content = "Generating file...";	0
26433903	26429047	Windows Phone ToastNotification cancellation	toast.SuppressPopup = true;\nToastNotificationManager.CreateToastNotifier().Show(toast);	0
2485839	2483235	Hiding Row in DataGridView Very Slow	DataGridView myGridView = new DataGridView();\nDataView myDataView = myTable.DefaultView;\nmyGridView.DataSource = myDataView; // DataView that allows row filtering\n\nmyDataView.RowFilter = string.Format("thisColumn <> '{0}'",match);  // this will hide all rows where "thisColumn" = match	0
26548430	26548300	ASP.NET - how do you change the way a JSON gets serialized?	public ActionResult getTransactionTotals(int itemID)\n    {\n        DBEntities db = new DBEntities();\n\n        var query = (from trans in db.Transactions\n                    // Linq query removed for brevity\n                        into selection\n                        select new TransactionAmount\n                        {\n                            name = selection.Key,\n                            amount = selection.Select(t => t.TransactionId).Distinct().Count()\n                        }).ToDictionary(k => k.name, v => v.amount);\n\n\n\n        return Json(query,JsonRequestBehavior.AllowGet);\n    }	0
1510213	1497881	Getting initial dimensions from inherited UserControl	public partial class BaseControl : UserControl\n{\n    private int _defaultWidth;\n    private int _defaultHeight;\n\n    public BaseControl()\n    {\n        InitializeComponent();\n\n        _defaultWidth = this.Width;\n        _defaultHeight = this.Height;\n    }        \n\n    protected override void SetBoundsCore(int x, int y, int width, int height, BoundsSpecified specified)\n    {\n        if (this.DesignMode)\n        {\n            width = _defaultWidth;\n            height = _defaultHeight;\n        }\n\n        base.SetBoundsCore(x, y, width, height, specified);\n    }\n}	0
474410	474047	How/Where to handle ConfigurationErrorsException in a windows service?	int GetIntFromConfigSetting(string settingName, int defaultValue)\n{\n   int retValue = defaultValue;\n   if(this.ContainsKey(settingName))\n   {\n      int sleepInterval;\n      if(Int32.TryParse(this[settingName], out sleepInterval)\n      {\n         retValue = sleepInterval;\n      }\n   }\n   return retValue;\n}	0
5393082	2454370	How to get block of unused ids in table with LTS?	var missing = from i in Enumerable.Range(strs.Min(),strs.Max())\n              where !strs.Contains(i)\n              select i;	0
7905393	7905354	Parse Text In String Using Regular Expressions	string text ="FW: Order Contract - 11009972; Customer - 5424 - TOYOTA CO; AE ID - 160SB Completed";\nRegex myRegex = new Regex(@"Contract - (\d+); Customer - (\d+)");\nvar match = myRegex.Match(text);\n// match.Groups[1].Value is the ContractId\n// match.Groups[2].Value is the CustomerID	0
4061815	4061807	Get only response headers	WebRequest.Method = "HEAD"	0
21289062	21288431	How to create drop down information box in C# Winforms?	private void button1_Click(object sender, EventArgs e) {\n  var helpInfo = new StringBuilder();\n  helpInfo.AppendLine("This is line one.");\n  helpInfo.AppendLine("This is line two.");\n  var textHelp = new TextBox() { Multiline = true,\n                                 ReadOnly = true,\n                                 Text = helpInfo.ToString(),\n                                 MinimumSize = new Size(100, 100)\n                                };\n  var toolHost = new ToolStripControlHost(textHelp);\n  toolHost.Margin = new Padding(0);\n  var toolDrop = new ToolStripDropDown();\n  toolDrop.Padding = new Padding(0);\n  toolDrop.Items.Add(toolHost);\n  toolDrop.Show(button1, button1.Width, 0);\n}	0
8424284	8424214	How to clear added entries of ListView?	lvSerialCode.Items.Clear();	0
31903568	31903504	Possible Interface use as variable? C#	IDictionary<String,Ivaluable[]> Sub=New Dictionary<String, Ivaluable[]>;\nIvaluable[] Sub1=new valueableObject[2]; // 2 is just an example\nSub.Add("whatever",Sub1);	0
28835844	28834216	How To Implement PerGraph LifeStyle	var scopedLifestyle = new LifetimeScopeLifestyle();\n\ncontainer.Register<ISomeType, SomeType>(scopedLifestyle);\n\nusing (container.BeginLifetimeScope())\n{\n    var some = container.GetInstance<SomeRootObjectDependingOnSomeType>();\n    some.Execute();\n}	0
18732719	18732672	How to change the Language to japanese in the Language Bar dynamically on for a windows application	InputLanguage.CurrentInputLanguage = InputLanguage.FromCulture(new System.Globalization.CultureInfo("ja-JP"));	0
16895226	16860013	Convert High Resolution PDF to Low Resolution PDF file C#	Doc doc = new Doc();\ndoc.Read(Server.MapPath("../mypics/sample.pdf"));\nusing (ReduceSizeOperation op = new ReduceSizeOperation(doc)) {\nop.UnembedSimpleFonts = false; // though of course making these true...\nop.UnembedComplexFonts = false; // ... would further reduce file size.\nop.MonochromeImageDpi = 72;\nop.GrayImageDpi = 72;\nop.ColorImageDpi = 144;\nop.Compact(true);\n}\ndoc.Save(Server.MapPath("ReduceSizeOperation.pdf"));	0
8043011	8042878	How to traverse a tree with many levels to find the previous and next element of the current element?	// finds the successor of node\nprocedure successor(node) \n{\n    // assuming you have the node for the id that you know.\n    // also I'm assuming you have some way to find its position \n    // in the child list\n\n    // if the parent has a child to the right\n    if(parent(node).children[position(node) + 1] != null)\n    {\n        return findLeftmost(parent(node).children[position(node) + 1]);\n        // find the leftmost node in the subtree rooted \n        // at the next sibling to the  right\n    }\n    else\n    {\n        return successor(parent(node));\n        // move up the tree\n    }\n}\n\n\n// finds the leftmost leaf node of the (sub)tree rooted at node\nprocedure findLeftmost(node)\n{\n    if(node.children.length == 0) // leaf node\n    {\n        return node;\n    }\n    else\n    {\n        return findLeftmost(node.children[0]); \n        // here I'm assuming the children are in the list from left to right, \n        // such that children[0] is the leftmost child.\n    }\n}	0
34449532	34449413	How to import Sleep function from kernel32?	Using System.Runtime.InteropServices;  \n\n....\n\npublic class NativeMethods\n{\n\n    [DllImport("kernel32")]\n    public static extern void Sleep(uint dwMilliseconds);\n}	0
747569	747554	Populate XDocument from String	XDocument.Parse	0
23673530	23673417	Find intersect of different dictionary values variable	var intersection = dictionary1\n.Where(kvp1 => \n   dictionary2.ContainsKey(kvp1.Key) \n   && dictionary2[kvp1.Key].classid = kvp1.Value.classid)\n.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);	0
25922907	25878739	Updating one entity with one context, and inserting a new with another context?	try\n            {\n                pcontext.SaveChanges();\n            }\n            catch (System.Data.Entity.Core.UpdateException e)\n            {\n\n            }\n\n            catch (System.Data.Entity.Infrastructure.DbUpdateException ex) //DbContext\n            {\n                Console.WriteLine(ex.InnerException);\n            }\n\n            catch (Exception ex)\n            {\n                Console.WriteLine(ex.InnerException);\n                throw;\n            }	0
19034914	19034854	How to localize a Windows.Forms .NET application?	ResourceFileName.ResourceName	0
34552496	34552392	How to get the shortest country name from an array in C#	var ordered = countries.OrderBy(x => x.Length);\nvar min = ordered.First();\nvar max = ordered.Last();\n\n//"The shortest country name is UK, it has 2 characters in its name"\nConsole.WriteLine("The shortest country name is {0}, it has {1} characters in its name",\n    min, min.Length);\n\n//"The longest country name is India, it has 5 characters in its name"\nConsole.WriteLine("The longest country name is {0}, it has {1} characters in its name",\n    max, max.Length);	0
17631785	17617777	How to link or reference a UI control such as a button in code	public abstract class CommonUIControls {\n    public static Button nextButton = null;\n}\n\npublic sealed partial class MainPage : Page\n{\n    public MainPage()\n    {\n        this.InitializeComponent();\n        CommonUIControls.nextButton = nextButton;\n    }\n}	0
8308081	8294177	GStreamer XOverlay lost after setting the Playbin state to NULL or READY	playBin.VideoSink.SetLockedState(true);\nplayBin.SetState(Gst.State.Ready);\nplayBin.Uri = @"file:///" + newFileName.Replace('\\', '/');\nplayBin.SetState(Gst.State.Paused);\nplayBin.VideoSink.SetLockedState(false);	0
4897580	4897510	Access Excel cell value in c#	Microsoft.Office.Interop.Excel.Range cell //it points to address A1\nobject obj=cell.Formula;	0
20267998	20267846	How to process large excel files?	Stream exportData = new MemoryStream(byte[] fileBuffer);	0
1380288	1380243	Application pool restart automaticly if file change in repositery	PropertyInfo p = typeof(HttpRuntime).GetProperty("FileChangesMonitor", \n                BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); \n\n            object o = p.GetValue(null, null); \n\n            FieldInfo f = o.GetType().GetField("_dirMonSubdirs", \n                BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.IgnoreCase); \n\n            object monitor = f.GetValue(o); \n\n            MethodInfo m = monitor.GetType().GetMethod("StopMonitoring", \n                BindingFlags.Instance | BindingFlags.NonPublic); \n\n            m.Invoke(monitor, new object[] { });	0
12039658	12039551	How to print various file types programmatically	ProcessStartInfo info = new ProcessStartInfo("[path to your file]");\ninfo.Verb = "PrintTo";\ninfo.Arguments = "\"[printer name]\"";\ninfo.CreateNoWindow = true;\ninfo.WindowStyle = ProcessWindowStyle.Hidden;\nProcess.Start(info);	0
3317976	3317727	reading a string from resx file sharpdevelop c#	Assembly.GetExecutingAssembly()	0
11633183	11632958	Recusive calls from a Catch block	if (retries < 3)\n{\n    Thread.Sleep(1000 * retries);\n    return UploadInvoice(filename);\n}	0
15464482	15464299	Regex expression to match even number of double quotation (") not match single one for CSV	splitArray = Regex.Split(subject, \n    @"\t        # Match a tab\n    (?=         # if the following regex matches after it:\n     (?:        # Match...\n      [^""]*""  # Any number of non-quotes, followed by a quote\n      [^""]*""  # ditto, to ensure an even number of quotes\n     )*         # Repeat as many times as needed\n     [^""]*     # Then match any remaining non-quote characters\n     $          # until the end of the string.\n    )           # End of lookahead assertion", \n    RegexOptions.IgnorePatternWhitespace);	0
30251052	30229417	Elasticsearch PUT documents in strange order	?sort=yourdatefield:desc	0
9998219	9998092	Suitable static DataStructure that is required to be thread safe in an ASP.net Application for concurrent access from various web clients	public class ThreadSafeList\n{\n    private List<Quiz> list = new List<Quiz>();\n    private object locker = new object();\n\n    private static ThreadSafeList instance = new ThreadSafeList();\n\n    private ThreadSafeList() { }\n\n    public static GetInstance()\n    {\n        return instance;\n    }\n\n    public void Add(Quiz q)\n    {\n        lock(locker) list.Add(q);\n    }\n\n    // whatever else you need to synchronize\n}	0
7850253	6933998	How to call a member through its parent's type that shadowed a parent class implementation	Public Sub TestCall(ByVal someAorBorC as A)\n    Convert.ChangeType(someAorBorC, someAorBorC.GetType()).Method()\nEnd Sub	0
26253942	26251639	EF:Many to many cascade delete	var AtoDelete= context.As.Include(a => a.Bs) .First(); //include is mandatory\ncontext.As.Remove(AtoDelete);\ncontext.SaveChanges();//deletes will be issued to AandB table also.	0
4796919	4796796	C# : Convert datetime from string with different format	CultureInfo enGB = new CultureInfo("en-GB"); \nstring dateString;\nDateTime dateValue;\n\n// Parse date with no style flags.\ndateString = "26/01/2011 00:14:00";\nDateTime.TryParseExact(dateString, "g", enGB, DateTimeStyles.None, out dateValue);	0
32923193	32923151	Remove last node from linked list c#	public void RemoveLast()\n    {\n        STACKnode current = head, last;\n\n        if (head == null) return;\n        if (head.next == null){\n            head = null;\n            return;\n        }\n\n        while (current.next != null)\n        {\n            last = current;\n            current = current.next;\n        }\n        last.next = null;\n    }	0
26126108	26125961	simple procedural maths program in C#	create a list of numbers\noutput prompt\nread input line\n\nwhile the input line had a value\n  parse the input value\n  add the parsed value to the list of numbers\n  output prompt\n  read input line\n\ncalculate the sum of the values divided by the length of the list\noutput the calculated average	0
20451905	20451833	In generate an Excel with DataTable I see : "A column named already belongs to this DataTable"	dt.Columns.Add(attr.DisplayName, pi.PropertyType);	0
20983078	20981209	How to check the title bar height of Xamarin Android activity	Android.App.ActionBar	0
1950443	1946466	WebDav how to check if folder exists?	PROPFIND /yourfolder HTTP/1.1\nContent-Type: application/xml\n\n<?xml version="1.0"?>\n<propfind xmlns="DAV:">\n   <prop>\n      <resourcetype />\n   </prop>\n</propfind>	0
14921610	14921478	Why when clicking mouse right button on listBox it's working everywhere in the listBox area?	private void listBox1_MouseDown(object sender, MouseEventArgs e) {\n        if (e.Button == MouseButtons.Right) {\n            var idx = listBox1.IndexFromPoint(e.Location);\n            if (idx >= 0 && listBox1.GetItemRectangle(idx).Contains(e.Location)) {\n                listBox1.SelectedIndex = idx;\n                contextMenuStrip1.Show(listBox1, e.Location);\n            }\n        }\n    }	0
21810949	21810713	Finding text within a text block	public string GetText(string text, string tag1, string tag2)\n    {\n        return Regex.Match(text, String.Format(":{0}[^:]?:(?<text>(\n|.)*):{1}[^:]?:", tag1, tag2)).Groups["text"].Value;\n    }	0
7609907	7609861	Application won't end VideoStreams and Exit	Application.ExitThread();	0
20926284	20925822	ASP MVC5 - Identity. How to get current ApplicationUser	string currentUserId = User.Identity.GetUserId();\nApplicationUser currentUser = db.Users.FirstOrDefault(x => x.Id == currentUserId);	0
15463999	15463912	Argument out of range - Card Shuffle	List<Card> shuffledDeck = new List<Card> ();\n\n   while (myDeck.Count > 0)\n   {\n      int c = myDeck.Count;\n\n      int n = rNumber.Next (0, c);\n      var value = myDeck[n];\n      shuffledDeck.Add(value);\n      myDeck.Remove(value);\n\n   }	0
5103451	5005838	CanvasAutorize - redirection to facebook permissions dialog clears the request_ids query string sent when user accepts an app request	public static string GetCanvasRedirectHtml(string url)\n        {\n            var fbApp = new FacebookApp();\n\n            string authUrl = string.Format("http://www.facebook.com/dialog/oauth?client_id={0}&redirect_uri={1}&scope={2}", fbApp.AppId, url, requiredAppPermissions);\n\n            if (string.IsNullOrEmpty(url))\n            {\n                throw new ArgumentNullException("url");\n            }\n\n            return "<html><head>" +\n                   "<script type=\"text/javascript\">\n" +\n                    "top.location = \"" + authUrl + "\";\n" +\n                    "</script>" +\n                   "</head><body></body></html>";\n        }	0
15704340	15696553	HttpClient+WebApi+Multiple Post + multiple parametres	routeTemplate: "api/{controller}/{action}/{id}",	0
12369260	12369125	How to execute package in C#?	var command = new OracleCommand(connection);\n  command.CommandText = "NameOfUser.NameOfPackage.NameOfStoredProcedure";	0
14555109	14555050	How to specify a sql connection string on c# that will always work even if you change directory?	Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\BaseDeDatos.mdf;Integrated Security=True;User Instance=True	0
9177454	9176988	Deserializing JSON to Object 	var js = new JavaScriptSerializer();\ndynamic dynObj =  js.DeserializeObject(jsonN);\nforeach (var obj in dynObj)\n{\n    if (obj.ContainsKey("name")) Console.WriteLine(obj["name"]);\n    else Console.WriteLine(obj["message"]);\n}	0
31463583	31463509	write to text box from a thread in after aborting thread WPF C#	if (!MyTextBox.Dispatcher.CheckAccess())\n{\n    MyTextBox.Dispatcher.Invoke(() => { MyTextBox.Text = myReceivedMessage.ToString(); });\n}\nelse\n{\n    MyTextBox.Text = myReceivedMessage.ToString();\n}	0
7836918	7836323	How can I do a query inside a query and set that as a condition for the main query	CREATE TEMPORARY TABLE TempTable (OrgName VARCHAR(10), Id INT, ParentID INT); \n\nINSERT INTO TempTable SELECT OrgName, Id, ParentID FROM org_table;\n\nWHILE EXISTS (SELECT TOP 1 1 FROM TempTable WHERE EXISTS(SELECT TOP 1 1 FROM TempTable TempTableParent WHERE TempTableParent.ID = TempTable.ParentID AND TempTableParent.ParentID IS NOT NULL) ) DO\n\nUPDATE TempTable SET ParentID = TempTableParent .parentID\nFROM TempTable\nINNER JOIN TempTable TempTableParent ON TempTableParent.id = TempTable.ParentID\nWHERE TempTable.ParentID IS NOT NULL AND TempTableParent.ParentID IS NOT NULL\n\nEND WHILE;\n\nSELECT * FROM TempTable	0
22686837	22686793	Converting decimal to binary with user input	int decToBin;\nConsole.WriteLine("Enter a number that will be converted to binary");\ndecToBin = Int32.Parse(Console.ReadLine());\nstring bin = Convert.ToString(decToBin, 2);\nConsole.WriteLine(bin);	0
4212354	4212317	How to write nested query in Linq	var result = tblArea.Where(x => !tblUserMaster.Any(m => m.areaid == x));	0
9266463	9260404	I need to parse 250 files, totalling at 1gb of data and upload it to a SQL server. Can I get more efficient than this?	class Program\n{\n    static void Main(string[] args)\n    {\n        var maxParallelism = Environment.ProcessorCount;\n        Parallel.ForEach(files, new ParallelOptions { MaxDegreeOfParallelism = maxParallelism }, ParseAndPersist);\n    }\n\n    public static void ParseAndPersist(FileInfo fileInfo)\n    {\n        //Load entire file\n\n        //Parse file\n\n        //Execute SQL asynchronously..the goal being to achieve maximum file throughput aside from any SQL execution latency\n\n    }\n}	0
7184819	7184721	C# listbox split to another 2 listboxes	using (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               string[] ipandport = line.split(":");\n               lstBoxIp.Items.Add( ipandport[0] );\n               lstBoxPort.Items.Add( ipandport[1] );\n            }\n        }	0
249519	249448	Data binding formatting to a DateTime column	private void textBox1_Validating(object sender, CancelEventArgs e)\n{\n    DateTime date;\n    if (!DateTime.TryParseExact(textBox1.Text, \n        "dd-MM-yyyy", \n        CultureInfo.CurrentCulture, \n        DateTimeStyles.None, \n        out date))\n    {\n        MessageBox.Show(textBox1.Text + " is not a valid date");\n        textBox1.Focus();\n        e.Cancel = true;\n        return;\n    }\n    if ((date < (DateTime) System.Data.SqlTypes.SqlDateTime.MinValue) ||\n        (date > (DateTime) System.Data.SqlTypes.SqlDateTime.MaxValue))\n    {\n        MessageBox.Show(textBox1.Text + " is out of range");\n        textBox1.Focus();\n        e.Cancel = true;\n        return;\n    }\n}	0
28465845	28398363	Change current implementation of basic MVVM to adhere to SOLID pattern	public interface IEditViewModel<TEntity>\n{\n    public EditResult<TEntity> EditEntity(TEntity entityToEdit)();\n}	0
5129285	5129225	An optimized stored procedure to replace this LINQ statement	CREATE PROCEDURE GetJobState @jobId int AS\nSELECT MIN(UnitStatus)\nFROM JobUnit \nWHERE Job_idJob = @jobId	0
21723982	21716618	Add index column on listview	private int counter;\npublic int Index\n{\n    get\n    {\n        counter++;\n        return counter;\n    }\n}	0
14051280	14051257	C#: Conversion from Int array to string array	int[] intarray = { 1, 2, 3, 4, 5 };\nstring[] result = intarray.Select(x=>x.ToString()).ToArray();	0
14092113	14087936	Windows 8 App reading and/or copying locked file	await file.CopyAsync(storageFolder);	0
18028601	18028549	regex to fix the input string	str = Regex.Replace(str, "\\.(?=;|,|$)", ".0");	0
24702672	24702413	How can I retrieve the previous value of a DataGridView cell using the CellValueChanged event?	private void dataGridView1_CellEndEdit(object sender, DataGridViewCellEventArgs e)\n{\n    newvalue = (int)dataGridView1[e.ColumnIndex, e.RowIndex].Value;\n}\n\nprivate void dataGridView1_CellBeginEdit(object sender, DataGridViewCellCancelEventArgs e)\n{\n    oldvalue = (int)dataGridView1[e.ColumnIndex, e.RowIndex].Value;\n}	0
2063239	2063191	Using Lambdas as Constraints in NUnit 2.5?	Assert.That( array, Is.All.Matches( (int x) => x%4 == 0 && x%100 != 0 || x%400 == 0 ));	0
24134631	24105959	using PLSQL dbms_output.put_line output in a winform app	CREATE OR REPLACE\nFUNCTION get_dbms_output(maxbytes IN NUMBER, buffer OUT VARCHAR2) RETURN NUMBER\nIS\n    l_line VARCHAR2(255);\n    l_done NUMBER := 0;\nBEGIN\n    LOOP\n        EXIT WHEN LENGTH(buffer) + 255 > maxbytes OR l_done = 1;\n        dbms_output.get_line(l_line, l_done);\n        buffer := buffer || l_line || CHR(10);\n    END LOOP;\n    RETURN l_done;\nEND get_dbms_output;\n/	0
1036971	1036948	How to set column header text for specific column in Datagridview C#	public Form1()\n    {\n        InitializeComponent();\n\n        grid.Columns[0].HeaderText = "First Column"; \n        //..............\n    }	0
3111560	3111517	Nhibernate : is it possible to make HQL generate SQL query with JOIN	"from accountlist a join fetch a.client"	0
17532314	17532263	C# copying distinct data from 1 datatable to another	secondTable = firstTable.AsEnumerable()\n    .GroupBy(row => new\n    {\n        Key = row.Field<string>("Key"),\n        Country = row.Field<string>("Country"),\n    })\n    .Select(group => group.First())\n    .CopyToDataTable();	0
11401093	11400976	How To Store data from the user in my variables by Immediate presses from the keyboard in C++ and C#(without pressing enter)	Console.ReadKey	0
16725995	16725922	16 bit registers with high/low byte implementation	using System.Runtime.InteropServices;\n...\n\n[StructLayout(LayoutKind.Explicit)]\nstruct X86Register {\n   [FieldOffset(0)] public byte   reg8;    // Like AL\n   [FieldOffset(1)] public byte   reg8h;   // Like AH\n   [FieldOffset(0)] public ushort reg16;   // Like AX\n   [FieldOffset(0)] public uint   reg32;   // Like EAX\n   [FieldOffset(0)] public ulong  reg64;   // Like RAX\n}	0
6035355	6035302	FileStream with locked file	FileStream Constructor (String, FileMode, FileAccess, FileShare)	0
11144094	11144040	Clear LSB of year and insert byte	int packetyear = year - year % 100 + packet[0];	0
31024388	31023139	Changing the ContentStringFormat property of a Label in code behind	var content = MyLabel.Content;\nMyLabel.Content = null;\nMyLabel.ContentStringFormat = "Bye {0}";\nMyLabel.Content = content;	0
8272306	8271442	Asynchronous coding - waiting for all returns - performance	Task[] tasks = new Task[3] \n    {\n        Task.Factory.StartNew(() => MethodA()),\n        Task.Factory.StartNew(() => MethodB()),\n        Task.Factory.StartNew(() => MethodC())\n    };\n\n//Block until all tasks complete.\nTask.WaitAll(tasks);	0
33419246	33417627	Move application from Apps to Background Processes in Task Manager	TopLevel = false	0
8403551	8403275	Side scrolling a tile map, Map getting messed up	i = row * columnCount + column;	0
21637201	21636733	DataGridView Missing Rows	_policyDataGrid.ScrollBars = ScrollBars.None;\n_policyDataGrid.ScrollBars = ScrollBars.Vertical;	0
15077346	15077196	check that values in lists match	stOldItems.All(x => lstNewItems.Any(y=> x.sItemPath == y.sItemPath));	0
3847599	3847432	Is my approach to assign values to an instance of custom EventArgs recommended?	Func<String, String>	0
4673214	4673139	Return all Generic List objects that implement an interface	return Animals.OfType<IHerd>().Cast<Animals>().ToList();	0
30873231	30873141	Converting strings to arrays c#	Private Sub SplitStrings(s As String)\n    Dim lines() As String = Split(s, "____")\n    For Each line As String In lines\n        Dim perLineTokens() As String = line.Split("___")\n    Next\nEnd Sub	0
21619570	21619373	Page fields are inaccessible due to protection level	protected string[] strFilePath = new string[5];\nprotected string[] strTitle = new string[5];\nprotected string[] strCity = new string[5];\nprotected string[] strCountry = new string[5];	0
21907244	21906626	c# create a user control on button press, won't show	var counter = new Counter();\nvar form = new Form();\nform.Controls.Add(counter);\nform.Show();	0
19561176	19561104	Unable to import or add row from a datatable	DataRow r = bucketdt.NewRow();\n        r = dosObject.SubCategoryDetails2(Convert.ToInt16(val)).Rows[0]; // overwrites r with a DataRow following another schema	0
15921998	15921964	SQL Server Query on todays date using datetime2	DECLARE @StartDate DATETIME2, @EndDate DATETIME2\n\nSET @StartDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()), 0)\nSET @EndDate = DATEADD(day, DATEDIFF(day, 0, GETDATE()+1), 0)\n\nSELECT CustomerID, Title, FirstName, LastName, AppStatus \n    FROM Customer     \n    WHERE DateAdded >= @StartDate AND DateAdded < @EndDate	0
25203505	25201819	Wpf/Silverlight gridview remove row blur effect	void Timer2_Click(object sender, EventArgs e)\n{\n    #region ListBox Remove And Effect / in Process\n    if (works.Count > 1)\n    {\n        //Work workTemp = works[0];  //Don't know if really needed\n          var fade = new DoubleAnimation()\n          {\n             From = 1,\n             To = 0,\n             Duration = TimeSpan.FromSeconds(5),\n          };\n       var item = //TheListBox.Items[];\n       Storyboard.SetTarget(fade, item);\n       Storyboard.SetTargetProperty(fade,\n                                    new PropertyPath(ListBoxItem.OpacityProperty));\n\n       var sb = new Storyboard();\n       sb.Children.Add(fade);\n       sb.Completed += sb_Completed;\n       sb.Begin(); \n\n    }\n}\n\n\n    void sb_Completed(object sender, EventArgs e)\n    {\n         works.RemoveAt(0); \n         //works.Add(workTemp);  //Don't know if really needed\n         DataContext = this; // BindGrid --Is that correct to define the context each time you click ? :(\n    }	0
33804452	33804355	How to get string between start and end character in C#	string str = "file_{AAA}_{BBB}.xml";\nvar regex = new Regex("(?<=\{)[^}]*(?=\})");\nvar matches = regex.Matches(str);	0
4248453	4248433	Intersect two arrays	IEnumerable<T>	0
503606	503564	How might I schedule a C# Windows Service to perform a task daily?	private Timer _timer;\nprivate DateTime _lastRun = DateTime.Now.AddDays(-1);\n\nprotected override void OnStart(string[] args)\n{\n    _timer = new Timer(10 * 60 * 1000); // every 10 minutes\n    _timer.Elapsed += new System.Timers.ElapsedEventHandler(timer_Elapsed);\n    _timer.Start();\n    //...\n}\n\n\nprivate void timer_Elapsed(object sender, System.Timers.ElapsedEventArgs e)\n{\n    // ignore the time, just compare the date\n    if (_lastRun.Date < DateTime.Now.Date)\n    {\n        // stop the timer while we are running the cleanup task\n        _timer.Stop();\n        //\n        // do cleanup stuff\n        //\n        _lastRun = DateTime.Now;\n        _timer.Start();\n    }\n}	0
25286298	25286254	Limit the string lenght with a defined character number	public static IEnumerable<string> SplitByLength(this string str, int maxLength)\n{\n    for (int index = 0; index < str.Length; index += maxLength)\n    {\n        yield return str.Substring(index, Math.Min(maxLength, str.Length - index));\n    }\n}	0
24673431	24654225	Stuck with Rx Observable SelectMany	files.ToObservable().SelectMany(f =>\n    {\n        var source = Observable.Defer(() => Observable.Start(() =>\n        {\n            ftpConnection.DownloadFile(avroPath, f.Name);\n            return Tuple.Create(true, f.Name);\n        }));\n        int attempt = 0;\n        return Observable.Defer(() => ((++attempt == 1)\n            ? source\n            : source.DelaySubscription(TimeSpan.FromSeconds(1))))\n            .Retry(4)\n            .Catch(Observable.Return(Tuple.Create(false, f.Name)));\n    }).ForEachAsync(res =>\n    {\n        if (res.Item1) Process(res.Item2);\n        else LogOrQueueOrWhatever(res.Item2);\n    }).Wait();\n\n    ProcessLogs();\n    ScheduleNExtDownloadRoutine();	0
20175486	20174336	Get focus on a ComboBox in DataGrid with tab key	private void comboCarbu_Initialized(object sender, EventArgs e)\n    {\n        foreach (var combobox in FindVisualChildren<ComboBox>(dataVoitures))\n        {\n            if (combobox.Name == "comboCarbu")\n            {\n                combobox.Focus();\n            }\n        }\n    }	0
15282362	15278213	how to do array of struct in c# like an type in vb6 using marshal	Type VB6Long64\n   LoValue As Long\n   HiValue As Long\nEnd Type	0
7487939	7486422	How do I read the msi output folder in a custom boostrapper/installer?	ManagementScope scope = new ManagementScope("\\\\.\\ROOT\\cimv2");\n\nObjectQuery query = new ObjectQuery("SELECT * FROM Win32_SoftwareElement WHERE SoftwareElementID='{YOUR WEB CONFIG GUID}'");\n\nManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);\n\nManagementObjectCollection queryCol = searcher.Get();\n\nforeach(ManagementObject m in queryCol)\n{\n  Console.Out.WriteLine("Path to web.config: {0}", m["Path"]);\n}	0
23098700	23096959	How to customize ServiceStack DateTime display format in its HtmlFormat snapshot	#show=fulldates	0
1341963	1341906	Replace '$' using Regex	Regex.Replace("@!$!", "!(.*)!", "replacement value");	0
1116739	1116720	How to read a singly linked list backwards?	IEnumerable<T> Reverse (Node head) {\n    Stack<Node> nodes = new Stack<Node>();\n    while(head != null) {\n        nodes.Push(head);\n        head = head.Next;\n    }\n    while(nodes.Count > 0) {\n        yield return nodes.Pop().Value;\n    }\n}	0
21413679	21412397	SyncFusion Grid - replicating Excel's Shift+Enter behaviour	void Grid_KeyDown(object sender, KeyEventArgs e)\n{\n    if ((e.KeyCode & Keys.Enter) == Keys.Enter && e.Modifiers == Keys.Shift)\n    {\n        grid.CurrentCell.Move(GridDirectionType.Up, 1, false);\n        e.Handled = true;\n    }\n}	0
7160185	7160122	getting arraylist from BulletedList control	string listCount = blistselected.Items.Count;\nstring[] array = new string[listCount];\nfor (int i=0; i<blistselected.Items.Count; i++) \n{\n    array[i] = blistselected.Items[i].Text;\n}	0
23682512	23648469	Using ClosedXML how to adjust row height to content?	worksheet.Rows().AdjustToContents();	0
27340276	27340228	Failed to connect to the database connection string	"Data Source=192.168.0.3,14330;Network Library=DBMSSOCN;Initial Catalog=master;Integrated Security=False;User ID=sa;Password=123456789;"	0
1623657	1620269	Entity Framework: Set back to default value	/// <summary>\n/// Sets all properties on an object to modified.\n/// </summary>\n/// <param name="context">The context.</param>\n/// <param name="entity">The entity.</param>\nprivate static void SetAllPropertiesModified(ObjectContext context, object entity) {\n    var stateEntry = context.ObjectStateManager.GetObjectStateEntry(entity);\n    // Retrieve all the property names of the entity\n    var propertyNames = stateEntry.CurrentValues.DataRecordInfo.FieldMetadata.Select(fm => fm.FieldType.Name);\n    foreach(var propertyName in propertyNames) {// Set each property as modified\n        stateEntry.SetModifiedProperty(propertyName);\n    }\n}	0
14146939	13721212	UltraWinGrid Column Within a Column	void ultraGrid1_InitializeLayout(object sender, Infragistics.Win.UltraWinGrid.InitializeLayoutEventArgs e)\n{\n    UltraGridBand band = e.Layout.Bands[0];\n    band.ColHeadersVisible = false;\n    ColumnsCollection columns = band.Columns;\n\n    UltraGridGroup group0 = band.Groups.Add("group0");\n    group0.Header.Caption = "";\n    UltraGridGroup group1 = band.Groups.Add("group1");\n    group1.Header.Caption = "Header 1";\n    UltraGridGroup group2 = band.Groups.Add("group2");\n    group2.Header.Caption = "Header 2";\n\n    columns[0].Group = group0;\n    columns[1].Group = group1;\n    columns[2].Group = group1;\n    columns[3].Group = group2;\n    columns[4].Group = group2;\n\n}	0
8810355	8799409	Get current ClickOnce's application publisher name?	...\n    var publisher = GetPublisher("My App Name");\n    ...\n\n    public static string GetPublisher(string application)\n    {\n        using (var key = Registry.CurrentUser.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Uninstall"))\n        {\n            var appKey = key.GetSubKeyNames().FirstOrDefault(x => GetValue(key, x, "DisplayName") == application);\n            if (appKey == null) { return null; }\n            return GetValue(key, appKey, "Publisher");\n        }\n    }\n\n    private static string GetValue(RegistryKey key, string app, string value)\n    {\n        using (var subKey = key.OpenSubKey(app))\n        {\n            if (!subKey.GetValueNames().Contains(value)) { return null; }\n            return subKey.GetValue(value).ToString();\n        }\n    }	0
9125115	9125016	Get url from a text	(http|ftp|https)://([\w+?\.\w+])+([a-zA-Z0-9\~\!\@\#\$\%\^\&\*\(\)_\-\=\+\\\/\?\.\:\;\'\,]*)?	0
24753134	24753099	Convert multidimensional Array (Object[,]) to string[]	string[] rowCells = cells.Cast<string>().ToArray();	0
13746013	13745904	LINQ Lambda, Group by with list	List<Filter_IDs> filterids = ef.filterLine.Select(o => new { objectType = o.objectType, object_id=o.object_id})\n    .GroupBy(fl => fl.objectType).ToList()\n    .Select(fl => new Filter_IDs { type = fl.Key, objects = fl.Select(x => x.object_id).ToList() })\n    .ToList();	0
23752720	23752561	Generic function with variable behavior depending on type in C#	if(typeof(S) == typeof(int))	0
26751494	26725385	How to save data changed in DXGrid to database	NewItemRowPosition.Top	0
29250419	29208459	Apply Formatting to TotalsRow using EPPlus	FileInfo newFile = new FileInfo(@"C:\Temp.xslx");\n\nusing (ExcelPackage package = new ExcelPackage(newFile))\n{\n    //Create the Worksheet\n    var sheet = package.Workbook.Worksheets.Add("Sheet1");\n    //Read the table into a sheet\n    var range = sheet.Cells["A1"].LoadFromDataTable(dtMain, true);\n\n    sheet.Tables.Add(range, "data");\n    //Now format the table...\n    var tbl = sheet.Tables[0];\n    tbl.ShowTotal = true;\n\n    //create a custom style\n    string stylename = "StyleName";\n    var style = package.Workbook.Styles.CreateNamedStyle(stylename);\n\n    tbl.Columns[SomeName].TotalsRowFunction = RowFunctions.Sum;\n\n    style.Style.Numberformat.Format = "#,###.00";\n    //apply style to totals row\n    sheet.Cells[sheet.Dimension.End.Row, colcount].Style.Numberformat.Format = c.Format;\n\n    //assign the style to the column\n    tbl.Columns[SomeName].DataCellStyleName = stylename;\n}\n\nrange.AutoFitColumns();\n\n// save our new workbook and we are done!\npackage.Save();	0
15262594	15262373	Require help to match a Regex pattern in c#	"Sec\. [A-Z\d]+\.([A-Z\d]+\.)?"\s?	0
20409362	20401789	How to get IParseTree in ANTLR4?	IParseTree tree = SpinParser.expr();	0
28360806	28357614	How discretely defined visibility of my assemblies types?	project Entity\nproject Database\nproject Server\nproject UserInterface	0
29939460	29937895	How to select the child node in TreeView in c# windows form	foreach (TreeNode tn in treeView1.Nodes)\n{\n   // get parent node here\n   foreach (TreeNode child in tn.Nodes)\n   {\n     //get child node here\n   }\n}	0
1718618	1718554	C# Keeping Pipes Open	using (QstWriter = new StreamWriter(IPCPipe))	0
9357995	9357956	linq how to pull an int col and compare with 0	bool bPresent = (from DataRow r in dsInternalInformation.Tables[0].Rows\n                 where (int)r["QstnCount"] > 0 select r).Any();	0
4694754	4694677	Regex to get the tags	Regex regExfont = new Regex(@"<font name=""arial""[^>]*>.*</font>");\n MatchCollection rows = regExfont.Matches(string);	0
17206372	17206240	Populating Two Dropdownlist on PageLoad	DataSet ds = GetAllCategory();\n    if (ds.Tables.Count > 0)\n    {\n        DropDownList1.DataTextField = "identifier";\n        DropDownList1.DataValueField = "OS_ID"; //Change field to one you want.\n        DropDownList1.DataSource = ds.Tables[0];\n        DropDownList1.DataBind();\n    }\n\n   if(DropDownList1.Items.Count > 0)\n   { \n       DropDownList1.SelectedIndex = 0;\n       DropDownList1_SelectedIndexChanged(this,null);\n   }	0
29820644	29820568	How can I make a textbox only accept a valid email?	try\n        {\n            var eMailValidator = new System.Net.Mail.MailAddress("xyz@blabla.com");\n        }\n        catch (FormatException ex)\n        {\n            // wrong e-mail address\n        }	0
7468653	7468592	how to bind the value from dataset to gridview footer control?	protected void yourNiceGridViewControl_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n  if (e.Row.RowType == DataControlRowType.Footer)\n  {\n    TextBox myTextBox = e.Row.FindControl("txtFooter") as TextBox;\n\n    if( myTextBox != null ) \n    {\n\n      myTextBox.Tex= ds.Tables[0].Rows[0]["MyFirend"].ToString();\n    }\n  }\n}	0
1255000	1254953	How to make GUI wait for windows service?	controller.WaitForStatus(ServiceControllerStatus.Running);	0
24396421	24375532	TypeLoadException from Mono	set MONO_LOG_LEVEL=debug	0
7390611	7390544	How to Update a C# chart control using databinding	Object lockOnMe = new Object();\n\n... in your Add loop\n\n(int i = 0; i < dacPoints.Count; i += 1) { \n    TimeSpan span = new TimeSpan(0, 0, i + 1); \n    lock (lockOnMe) { \n        presenter.addPoint(span.ToString(), dacPoints[i]); \n    } \n    System.Threading.Thread.Sleep(200); \n}\n\n... when calling DataBindXY()\n\nlock (lockOnMe) {\n    // Note that I copy the lists here.  \n    // This is because calling DataBindXY is not necessarily a serial, \n    // blocking operation, and you don't want the UI thread touching \n    // these lists later on after we exit the lock\n    chart.Series[0].Points.DataBindXY(xAxis.ToList(), yAxis.ToList());\n}	0
1941548	1941450	C# match and export based on listbox textfile and wildcard	//Popullate listItems from your ListBox     \nvar listItems = new string[] { "Apple", "Orange", "Pineapple" };\nvar writers = new StreamWriter[listItems.Length];\nfor (int i = 0; i < listItems.Length; i++)\n{\n    writers[i] = File.CreateText(listItems[i] + ".txt");\n}\nvar reader = new StreamReader(File.OpenRead(bigFatFile));\n\nstring line;\nwhile ((line = reader.ReadLine()) != null)\n{\n    for (int i = 0; i < listItems.Length; i++)\n    {\n        if (line.StartsWith(listItems[i]))\n            writers[i].WriteLine(line);\n    }\n}\nreader.Close();\nforeach (var writer in writers)\n    writer.Close();	0
25992643	25992447	Struggling with C# generic HashSet declaration	public enum Color { Red, Yellow, Green, Blue }    \npublic class ColorSet : HashSet<Color> {}\n\nprivate void setColors(ColorSet colors = null)\n{\n    if (colors == null)\n        colors = new ColorSet {Color.Red, Color.Green};\n\n    ....\n}	0
3153052	3152996	How to "properly" override a base class method?	public class BaseClass {\n    public void Method() // Non-virtual\n    {\n          // Do required work\n\n          // Call virtual method now...\n          this.OnMethod();\n    }\n\n    protected virtual void OnMethod()\n    { // Do nothing\n    }\n }	0
28541603	26622147	How to get ADDED friends that are in a Contact List?	ArrayList UserList = new ArrayList();\n    var SkypeClient = new SKYPE4COMLib.Skype();\n    foreach (User User in skype.Friends)\n    {\n        if (User.BuddyStatus == SKYPE4COMLib.TBuddyStatus.budFriend)\n        {\n            UserList.Add(User.Handle);\n        }\n    }	0
1977864	1977843	Can I use reflection and a string to get/set the correct property of an object?	const string propPrefix = "UserVar";\n\nVendorObj o = new VendorObj();\nforeach (var item in userVars)\n{\n    int varNum = 0;\n    if (Int32.TryParse(item.VariableName, out varNum))\n    {\n        string name = String.Format("{0}Nbr{1}", propPrefix, varNum);\n        o.GetType().GetProperty(name).SetValue(o, "some value", null);\n    }\n}	0
19976772	19976349	Searching data depending on conditions	String drpClassString = ""\n\nIf(drpclass.SelectedIndex != 0)\n{\n  drpString = " and tblhomework.ClassCode='" + drpclass.SelectedItem.Value + "'"\n}\nString thrNameString = "";\nif(txt_tchrname.Text.Length != 0)\n{\nthrNameString = " and tblhomework.TshortCode='" + txt_tchrname.Text.ToString() + "'"\n}\nString dateString = ""\nif( txtdatesearch.Text.Length != 0)\n{\ndateString =" and DATE_FORMAT(tblhomework.DateCreated,'%d-%m-%y')='" + strDTentered1 + "'"\n}\n\n\nString sqlsearch = "SELECT tblhomework.ID,tblteacher.TEACHERNAME,tblclass.CLASSNAME,tblhomework.Title,tblhomework.HomeworkDetail,tblhomework.StudentsCode FROM tblhomework" +\n        " join tblclass on tblclass.CLASSCODE=tblhomework.ClassCode join tblteacher on tblteacher.TSHORTNAME=tblhomework.Tshortcode where 1 = 1" + drpClassString + thrNameString +dateString;	0
1535079	1534549	C#: How to change the region containing MDI children?	public class Form1 : Form\n{\nstatic void Main(string[] args) { Application.Run(new Form1()); }\n\npublic Form1()\n{\nthis.IsMdiContainer = true;\nPanel test = new Panel();\ntest.Dock = DockStyle.Top;\ntest.Height = 100;\nthis.Controls.Add(test);\n\nForm child = new Form();\nchild.MdiParent = this;\nchild.Text = "Child";\nchild.Show();\n}\n}	0
7978709	7928795	Cant select Items in Listbox when using Tabcontrol WPF	private void ListBox_selectionChanged(object sender, DragEventArgs e)\n{\n    e.handled = true;\n}	0
10747994	10747863	How to host wcf service programmatically on azure	private String GetRandomServiceIP(String roleName, String endPointName)\n{\n    var endpoints = RoleEnvironment.Roles[roleName].Instances.Select(i => i.InstanceEndpoints[endPointName]).ToArray();\n    var r = new Random(DateTime.Now.Millisecond);\n    int ipIndex = r.Next(endpoints.Count());\n    return endpoints[ipIndex].IPEndpoint.Address.ToString();\n}	0
12807341	12807058	Accessing many table's data through only one table (C# + SQL Server)	Create View Pokedata as\n    Select name_,  t1.type as Type1, t2.type as Type2, ability\n    From Kanto \n    inner Join Abilities on Kanto.abilityId = Abilities.abilityId\n    inner join KantoType as kt1 on Kanto.pok?monid = kt1.pok?monid and kanto.typeid1 = kt1.typeid\n    inner join on types as t1 on kt1.typeid = t1.typeid\n    inner join KantoType as kt2 on Kanto.pok?monid = kt2.pok?monid and kanto.typeid2 = kt2.typeid\n    inner join on types as t2 on kt2.typeid = t2.typeid	0
9236653	9236584	C# how to write multiple lines in a text file?	FileStream xuids = new FileStream(xuidspath, FileMode.Append);	0
1062697	1062469	How do I get access to the WCF service instance in the current context?	var myService = OperationContext.Current.InstanceContext.GetServiceInstance();	0
25120469	25120339	Read XMLNode errors from SoapException	var errors = XDocument.Parse(yourxmlstring)\n                .Descendants("errors")\n                .Select(e => new\n                {\n                    code = (int)e.Element("code"),\n                    desc = (string)e.Element("description")\n                })\n                .ToList();	0
2474338	2421033	Provide a URI as a parameter for an ODBC or OleDB provider connection string?	SqlConnection myconn = new SqlConnection( connstring );	0
12887488	12887464	Generic method to instantiate a variable of any type (including nullable struct)?	Type realType = Nullable.GetUnderlyingType(typeof(T));\nt = (T)Activator.CreateInstance(realType ?? typeof(T));	0
11188039	11188009	How to load user control at run time, in a aspx page?	UserControl uc = new UserControl();\nstring ID = "1";\nstring userControl ="UC" + ID + ".ascx";\nuc = LoadControl(userControl) as UserControl;\nPlaceHolder1.Controls.Add(uc); //some place holder to place controls	0
588268	587547	How to put in text when using XElement	new XElement("h1", "Text\u00A0to\u00A0keep\u00A0together");	0
14008180	14008090	How would I read and write encrypted XML files?	System.Security.Cryptography.Xml Namespace	0
938599	938585	Open other program's configuration files	var configMap = new ExeConfigurationFileMap {ExeConfigFilename = externalConfigurationFile};\nSystem.Configuration.Configuration externalConfiguration = ConfigurationManager.OpenMappedExeConfiguration(configMap, ConfigurationUserLevel.None);\n\nforeach (KeyValueConfigurationElement setting in externalConfiguration.AppSettings.Settings)\n{\n    ...\n}\n\ncurrentConfiguration.Save(ConfigurationSaveMode.Full);	0
8213659	8213578	Show most occured in rank order #	var query = File\n    .ReadLines("input.txt")\n    .GroupBy(x => x)\n    .Select(g => new { Key = g.Key, Count = g.Count() })\n    .OrderByDescending(i => i.Count)\n    .Take(20);\n\nforeach (var item in query)\n{\n    Console.WriteLine("{0,5} {1}", item.Count, item.Key);\n}	0
31372774	31372589	Windowed and Windowless Applications Together	bool IsProcessRunning(string processName)\n{\n        return (System.Diagnostics.Process.GetProcessesByName(processName).Length != 0);\n}	0
341200	341175	datetime.parse and making it work with a specific format	DateTime.ParseExact(input,"yyyyMMdd HH:mm",null);	0
31115814	31115597	changing screen resolution programmatically	nircmd.exe setdisplay 1366 768 32	0
20063907	20063462	translating if to for loop	void OnNextBuild()\n{\n  if (PrimeBuilders.Count < 2) return;\n  int i = PrimeBuilders.IndexOf(_building_instance.BuildingID);\n\n  if(i != -1)\n  {\n      if(++i == PrimeBuilders.Count) i = 0;\n      _building_instance = _simulation_manager.\n                            GetCity().\n                            GetBuildingInstance(PrimeBuilders[i]);\n\n      _interface_state_manager.SetNextState(InterfaceState.ShowBuildUnitsPanel);\n  }\n}	0
4420691	4420669	Displaying image on a Panel	panel.BackgroundImage = Image.FromFile(open.FileName);	0
10353786	10249808	Using Web Service Method for Insert data to Database with Auto Increment for the Primary Key	sampleWS s = new sampleWS();\ns.addExam(100000000, bla, bla);	0
11227570	11227529	Disable Buttons C#	if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem )	0
9756917	9756797	Read console input as enumerable - one statement?	public static IEnumerable<string> ReadLines()\n{\n  string line;\n  while(null != (line = Console.ReadLine()))\n    yield return line;\n}\n\npublic static void Main()\n{\n  string input = string.Join(ReadLines(), Environment.NewLine);\n}	0
12702262	12702167	Text/Font scaling on page printing	g.TranslateTransform(pointX, pointY);\ng.ScaleTransform(1, 2);\ng.TranslateTransform(-pointX, -pointY);\n\ng.DrawString(myText, myFont, myBrush, pointX, pointY);	0
7402451	7402393	LINQ, simplifying expression - take while sum of taken does not exceed given value	int current=0;\nvar selection = products.TakeWhile(p => (current = current + p.Cost) <= credit);	0
3254534	3254426	IntPtr to String and long?	long l = Marshal.ReadInt64(result, 9);\nreturn l;	0
31855561	31824995	Castle.Windsor instantiating wrong version of SqlConnection with Dapper	container.Register(Component.For<IDbConnection>().ImplementedBy<SqlConnection>()\n        .LifestyleTransient()\n        .UsingFactoryMethod(() => new SqlConnection          \n       (ConfigurationManager.ConnectionStrings["DbConnectionString"].ConnectionString)));	0
30875217	30874452	Change folder icon in asp tree view control	I would use CSS to do that.  I would add a class element on the ASP\n\n    <asp:LinkButton ID="lnk" runat="server" Text='<%# Eval("LibName") %>' CommandName="Update"\n CommandArgument='<%# Eval("LibID") %>' Visible='<%# Eval("FolderVisibility") %>'  Class='Visible<%# Eval("FolderVisibility") %>'></asp:LinkButton>\n\n\nSo in the HTML the class will come out like "Class='VisibleTrue'" or "Class='VisibleFlase'" \n\nin the CSS you can create a two classes\n\n>     .VisibleFlase{\n//Icon css here\n},\n.VisibleTrue{\n//icon Css here\n\n}	0
1221528	1221468	How to increase spacing between lines in webbrowser control	line-height	0
30199418	30199224	Draw String to centre of elipse using C#	RectangleF bounds = new RectangleF(x, y, width, height);\nusing (StringFormat format = new StringFormat()) {\n    format.Alignment = StringAlignment.Center;\n    format.LineAlignment = StringAlignment.Center;\n    graphicsObj.DrawText("Number", SystemFonts.Default, Brushes.Black, bounds, format);\n}	0
9079192	9078419	.NET Windows service executes batch file from system32 folder not install folder	System.IO.Directory.SetCurrentDirectory(System.AppDomain.CurrentDomain.BaseDirectory);	0
5037258	5037050	IOException File Copy unhandled. When uploading image from a picturebox	if (open_dialog.ShowDialog() != DialogResult.Cancel)\n    {\n        if (uploadpic_pb.BackgroundImage != null) uploadpic_pb.BackgroundImage.Dispose();\n        uploadpic_pb.BackgroundImage = Image.FromFile(open_dialog.FileName);\n        // etc...\n    }	0
17457746	11893631	Unpredictable behavior of Action invocation in Caliburn Micro	protected override void Configure()\n    {\n      ConventionManager.AddElementConvention<ListPicker>(ListPicker.ItemsSourceProperty, "SelectedItem", "SelectionChanged").ApplyBinding = \n        (viewModelType, path, property, element, convention) => {\n         if (ConventionManager.GetElementConvention(typeof(ItemsControl)).ApplyBinding(viewModelType, path, property, element, convention))\n         {\n             ConventionManager.ConfigureSelectedItem(element, ListPicker.SelectedItemProperty, viewModelType, path);\n             return true;\n         }\n         return false;\n     }; }	0
5269871	5268880	Image from webbrowser control to picturebox - C#	mshtml.HTMLWindow2Class w2 = webBrowser1.Document.Window.DomWindow as mshtml.HTMLWindow2Class;\nw2.execScript("var ctrlRange = document.body.createControlRange();ctrlRange.add(document.getElementById('img1'));ctrlRange.execCommand('Copy');", "javascript");\nImage image2 = Clipboard.GetImage();\npictureBox1.Image = image2;	0
25948425	25948383	Read a text file and add to a list	List<Store> stores = new List<Store>();\n            var storeTemp = new Store();\n\n        foreach (string line in File.ReadAllLines(@"C:\Store.txt"))\n        {\n            // You needto create a new instance each time\n            if (line.Contains("Store ID: "))\n                storeTemp.ID = line.Substring(10);\n            if (line.Contains("Name: "))\n                storeTemp.name = line.Substring(6);\n            if (line.Contains("Branch Number: "))\n                storeTemp.branchNO = Convert.ToInt32(line.Substring(15));\n            if (line.Contains("Address: "))\n                storeTemp.address = line.Substring(9);\n            if (line.Contains("Phone: "))\n            {\n                storeTemp.phoneNumber = Convert.ToInt32(line.Substring(7));\n                stores.Add(storeTemp);\n                storeTemp = new Store(); // You need to recreate the object, otherwise you overwrite same instance\n\n            }\n        }	0
25348326	25348112	sending email using gmail from asp.net	smtp.UseDefaultCredentials = false;	0
11374341	11207243	WCF Percall mode and threadstatic variables	public class OperationContextExtension : IExtension<OperationContext>\n{\n    public void Attach(OperationContext owner)\n    {\n        this.Current = new Dictionary<string, string>();\n    }\n\n    public void Detach(OperationContext owner)\n    {\n        this.Current = null;\n    }\n\n    public Dictionary<string,string> Current { get; set; }\n}	0
6240083	6240050	Splitting a comma delimited text file	"[^"]*"|\S+	0
10264376	10263962	Find parent control of ToolStripMenuItem	((ContextMenuStrip)(((ToolStripMenuItem)sender).Owner)).SourceControl	0
713547	713435	Replacing numbers in strings with C#	(?<!\.[0-9a-z]*)[0-9]	0
19273440	19272840	Auto generated Gridview - Change columns width	private void grv_RowDataBound(object sender, GridViewRowEventArgs e)\n    {\n\n        if (e.Row.RowType == DataControlRowType.Header)\n        {\n\n                   e.Row.Cells[0].Width = new Unit("5%");\n                   e.Row.Cells[1].Width = new Unit("7%");\n                   e.Row.Cells[2].Width = new Unit("12%");\n                   e.Row.Cells[3].Width = new Unit("12%");\n                   e.Row.Cells[4].Width = new Unit("7%");\n                   e.Row.Cells[5].Width = new Unit("7%");\n                   e.Row.Cells[6].Width = new Unit("23%");\n                   e.Row.Cells[7].Width = new Unit("22%");\n                   e.Row.Cells[8].Width = new Unit("5%"); \n        }\n\n    }	0
8191276	8191212	ExecuteStoreQuery passing parameter to SQL statement	var node = db.ExecuteStoreQuery<Node>(@"\n    with c as (\n        select Id, Name, ParentId,[0] as level\n        from Department d\n    union all\n        select d.Id, d.Name, d.ParentId, [level] + 1\n        from Department d\n        join c on d.ParentId = c.Id)\n    select * from c where c.Id = @Id"                                                         \n"Departments", \nSystem.Data.Objects.MergeOption.NoTracking, \nnew SqlParameter{ ParameterName = "id", Value = department.Id});	0
3164945	3164424	Checking a HTML string for unopened tags	var htmlDoc = new HtmlDocument();\n\nhtmlDoc.LoadHtml(\n    "WAVEFORM</u> YES, <u>NEGATIVE AUSCULTATION OF EPIGASTRUM</u> YES,");\n\nforeach (var error in htmlDoc.ParseErrors)\n{\n    // Prints: TagNotOpened\n    Console.WriteLine(error.Code);\n    // Prints: Start tag <u> was not found\n    Console.WriteLine(error.Reason); \n}	0
11639839	11639701	Generic Method for retrieving an entity model	var objectSet = entities.GetType( ).GetProperties( )\n    .Where( p => p.PropertyType.IsGenericType \n         && p.PropertyType.GetGenericArguments( )[ 0 ].Name == typeof( T ).Name )\n    .Select( p => p.GetValue( entities, null ) as ObjectSet<T> )\n    .First( );\nreturn objectSet.ToList( );	0
1590820	1590805	ASP.NET Processing lambdas	var validemails = emails.Where(p=>IsValidFormat(p.Value)).Select(kv => kv.Value);	0
26234432	26229765	iBeacon support for Windows Phone devices	var themometerServices = await Windows.Devices.Enumeration .DeviceInformation.FindAllAsync(GattDeviceService .GetDeviceSelectorFromUuid( GattServiceUuids.HealthThermometer), null);	0
20059388	20059345	Iterating through object properties in IList without a loop	MarkettingNames = string.Join(", ", GroupA.MarkettingEmployees.Select(e => e.Name));	0
22662803	22662655	How do I give student score that are equal same rank	static void Main(string[] args)\n    { \n        using (var \n\ndb = new SchoolEntities())\n        {\n            double currentScore = 0;\n            int rank= 0;\n            int savedRank;\n        var query = db.ScoreSummaries\n            .OrderByDescending(x => x.TotalScore).ToList();\n\n        foreach (var item in query)\n        {\n\n      rank+= 1;\n      if(item.TotalScore == current score)\n       {\n        savedRank = savedRank\n       }\n       else\n       {\n         savedrank = rank;\n        }\n\n            Console.WriteLine("{0},{1},{2}", item.TransactionID, item.TotalScore, savedrank);\n            currentScore = item.totalScore;\n            }\n            Console.WriteLine("Pls press any key to exit");\n            Console.ReadKey();\n        }\n    }	0
15403647	15249619	Linq xml to object - How to populate a Collection<string>	IEnumerable<Accommodation> temp = \n    (from x in doc.Descendants("Accommodation")\n        select new Accommodation()\n        {\n            Categories = new Collection<string>(\n                x.Descendants("Categories").SelectMany(categories \n                    => categories.Elements("Category").Select(category \n                        => category.Attribute("Id").Value ?? "")).ToList())\n        }).ToList();	0
21563887	21563711	Show notification in DragDrop method without maintaining sender's DoDragDrop	protected override void OnDragDrop(DragEventArgs drgevent) {\n        this.BeginInvoke(new Action(() => {\n            MessageBox.Show(this, "Error");\n        }));\n        base.OnDragDrop(drgevent);\n    }	0
299143	299094	C#: How do I do simple math, with rounding, on integers?	int height2 = (int)Math.Round(width2 * (height1 / (float)width1));	0
4220404	4220371	Abstract/Virtual Members to Provide Common & Derived Combined Functionality - C#	public abstract class Post {\n\n    // Default validation technique\n    public void Validate()\n    {\n        // your base validation\n        // Then call the specific validation technique\n        ExtraValidate();\n    }\n\n    // Forces subclasses to provide validation technique\n    protected abstract void ExtraValidate();\n}	0
34163043	34162680	Rotate camera in function of direction of ball	Vector3 offset = new Vector3(1,1,0);\ntransform.position = ball.transform.position - ball.GetComponent<Rigidbody>().velocity / ball.GetComponent<Rigidbody>().velocity.magnitude + offset;\ntransform.LookAt (ball.transform.position);	0
22446481	22446110	How can I redirect requests under a folder to another?	bundles.Add(new StyleBundle("~/bundles/style/main").Include("~/Content/styles/main.css", new CssRewriteUrlTransform()));	0
33309948	33307928	Serializing an object to XML and appending it to XML file	// same code till this\n\n// get horse element from horseXml\nXmlElement horseEl = horseXml.DocumentElement; //[1] get the doc element\n\n// assign xmldb to xml document\nvar xmlDb = new XmlDocument();\nxmlDb.Load(xmlDbFilepath);\n//XmlNode root = xmlDb.DocumentElement; [2] removed\n\n// add horseEl to root of xmlDb\n//var newRoot = root.AppendChild(clonedHorseEl); [3] removed\nvar xe = xmlDb.CreateElement("Horse"); //[4] Create new Horse element on xmlDb\nxe.InnerXml = horseEl.InnerXml; //[5] copy horseEl content\nxmlDb.DocumentElement.AppendChild(xe);\n\nxmlDb.Save(xmlDbFilepath);	0
30244849	30244725	Checking the value of a word in different dictionary then in the loop	foreach(var word in dict1.Where(w=>dict2.ContainsKey(w.Key) && dict2[w.Key]>5))\n{\n    //dowork\n}	0
10367960	10367797	Populate an array/list with sums	using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\n\nnamespace ConsoleApplication1\n{\n    class Program\n    {\n\n        struct addition_pairs{\n            public int first;\n            public int second;\n        }\n\n        static void Main(string[] args)\n        { \n\n         List<addition_pairs> main_list;\n         main_list = new List<addition_pairs>();\n       //TODO call populate_list and choose how many sets you want.\n\n        }\n\n        private void populate_list(int how_many, List<addition_pairs> list)\n        {\n            for (int i = 0; i < how_many; i++)\n            {\n                Random random = new Random();\n                int randomNumber1 = random.Next(0, 10);\n                addition_pairs insert = new addition_pairs();\n                insert.first = randomNumber1;\n                insert.second = random.Next(0, 10-randomNumber1);\n                list.Add(insert);\n            }\n\n        }\n    }\n}	0
11552285	11552229	Behavior of C# with Nullables	1] default(int?) will always return 'null'\n2] null | <anything> returns 'null'	0
14167839	14167621	Get a screenshot of the web browser control?	using (var browser = new System.Windows.Forms.WebBrowser())\n{\n     browser.DocumentCompleted += delegate\n     {\n         using (var pic = new Bitmap(browser.Width, browser.Height))\n         {\n             browser.DrawToBitmap(pic, new Rectangle(0, 0, pic.Width, pic.Height));\n             pic.Save(imagePath);\n         }\n     };\n\n     browser.Navigate(Server.MapPath("~") + htmlPath); //a file or a url\n     browser.ScrollBarsEnabled = false;\n\n     while (browser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)\n     {\n         System.Windows.Forms.Application.DoEvents();\n     }\n}	0
14223477	14223342	Deep search within a multidimensional object	foreach (PropertyInfo pi in o.GetType().GetProperties())	0
4151317	4133061	XNA field of view in 2D	double CanonizeAngle(double angle)\n    {\n        if (angle > Math.PI)\n        {\n            do\n            {\n                angle -= MathHelper.TwoPi;\n            }\n            while (angle > Math.PI);\n        }\n        else if (angle < -Math.PI)\n        {\n            do\n            {\n                angle += MathHelper.TwoPi;\n            } while (angle < -Math.PI);\n        }\n\n        return angle;\n    }\n\n    double VectorToAngle(Vector2 vector)\n    {\n        Vector2 direction = Vector2.Normalize(vector);\n        return Math.Atan2(direction.Y, direction.X);\n    }\n\n    bool IsPointWithinCone(Vector2 point, Vector2 conePosition, double coneAngle, double coneSize)\n    {\n        double toPoint = VectorToAngle(point - conePosition);\n        double angleDifference = CanonizeAngle(coneAngle - toPoint);\n        double halfConeSize = coneSize * 0.5f;\n\n        return angleDifference >= -halfConeSize && angleDifference <= halfConeSize;\n    }	0
22802946	22802945	How can I get only projects from the solution?	var projects = CommonMethods.GetProjects(solution).Where(item => item.FullName != string.Empty).ToList();	0
17383747	17383594	UIRobot controller and program in C#	string command = "ENABLE;";	0
10026516	10025995	How to get Left outer join in Linq?	var result = from customer in customers  \n                   from personalFirst in personal  \n                       .Where(pf => pf.Field == "First Name" && pf.C_ID == customer.C_ID)  \n                       .DefaultIfEmpty() \n                   from personalLast in personal  \n                       .Where(pl => pl.Field == "Last Name" && pl.C_ID == customer.C_ID)  \n                       .DefaultIfEmpty()  \n                    where customer.C_ID == 2  \n                    select new { customer.C_ID, Name = (personalFirst != null ? personalFirst.Value : "") + " " + (personalLast != null ? personalLast.Value : "") };	0
7836278	7836256	C# Add items if they are between a date	// Presumably you can determine these once... (possibly rename to earliestValid\n// and latestValid, or something like that?)\nDateTime from = new DateTime(fromYear, fromMonth, fromDay);\nDateTime to = new DateTime(toYear, toMonth, toDay);\n\n// Then for each candidate...\n...\nDateTime date = new Date(year, month, day);\nif (date >= from && date <= to)\n{\n    listBox1.Items.Add(...);\n}	0
25587007	25586755	Adding user controls to the winforms statusstrip control	public class BindableToolStripStatusLabel : ToolStripStatusLabel, IBindableComponent\n\npublic class BindableStatusBarLabel :  ToolStripLabel, IBindableComponent\n{\n    private ControlBindingsCollection _bindings;\n\n    private BindingContext _context;\n\n    public BindingContext BindingContext\n    {\n        get\n        {\n            if (_context == null)\n            {\n                _context = new BindingContext();\n            }\n            return _context;\n        }\n        set\n        {\n            _context = value;\n        }\n    }\n\n    public ControlBindingsCollection DataBindings\n    {\n        get\n        {\n            if (_bindings == null)\n            {\n                _bindings = new ControlBindingsCollection(this);\n            }\n            return _bindings;\n        }\n    }\n}	0
16187495	16187461	How to merge 2 dictionaries	private Dictionary <int, aor.PhysicalObject> merger;\n\nmerger = Enumerable\n         .Concat(  from a in log\n                             .InitialState\n                             .Agents\n                             .Agent\n                    select a\n                 ,  from o in log\n                              .InitialState\n                              .Objects\n                              .Object  \n                     select o\n                ).ToDictionary(d => Convert.ToInt32(d.id)\n                                ,  d => d as aor.PhysicalObject);	0
8443725	8443675	Creating a dropdownlist c# mvc3	Html.DropDownList("Status", \n    new SelectListItem[]{ new SelectListItem{ Text= "Showing", Value="Showing"},\n    //same for others\n});	0
23351546	23351133	How to load html source without the URL?	internal Dictionary<string, string> GetIDsAndXPaths()\n{\n    var web = new HtmlWeb();\n    var webidsAndXPaths = new Dictionary<string, string>();\n    var page = driver.PageSource; // Gets the source of the page last loaded by the browser\n\n    const string path = @"C:\temp\myHtml.html";\n    var sw = new StreamWriter(path, false);\n    sw.Write(page);\n    sw.Close();\n    const string url = path;\n    var doc = web.Load(page);\n    var nodes = doc.DocumentNode.SelectNodes("//*[@id]");\n    if (nodes == null) return webidsAndXPaths;\n    // more code to get ids and such\n    return webidsAndXPaths;\n}	0
14449456	14448856	Is there a way to find the HTMLDocument from the IHTMLEventObj passed from an onload event in IE?	Class HTMLWindowEvents2Sink\n{\n    public HTMLWindowEvents2Sink(IHTMLWindow2 eventSource)\n    {\n        this.eventSource=eventSource;\n    }\n    IHTMLWindow2 eventSource;\n    void AdviseEvent()\n    {\n        eventSource.load += this.HTMLWindow_onload; \n    }\n    ....\n}	0
11729958	11728150	How could a page be cached and expire upon folder change?	Response.AddFileDependency("Your folder path");	0
4098051	4098013	transfer from http to https asp.net c#	if (HttpContext.Current.Request.Url.Host.CompareTo("https://yourwebsite") != 0)\n{\n    HttpContext.Current.Response.Redirect("https://yourwebsite" + Context.Request.Url.PathAndQuery);\n}	0
32726168	32726109	Add new line to a text file in loop statement	WriteAllText()	0
5851950	5851912	Problem with setting visibility of controls in child master page in asp.net	Div1.Visible = false;	0
30988367	30983539	Changing elements in datagridview	private void eolGrid_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)\n    {\n        int rowNum = e.RowIndex;\n        DataGridViewCellStyle style = new DataGridViewCellStyle();\n\n        DateTime dateval = Convert.ToDateTime(eolGrid.Rows[rowNum].Cells[3].Value);\n\n        if ((dateval - date).TotalDays <= 0)\n            style.ForeColor = Color.Red;\n        else if ((dateval - date).TotalDays <= 14)\n            style.BackColor = Color.Red;\n        else\n            style.ForeColor = Color.Black;\n\n        eolGrid.Rows[rowNum].Cells[3].Style = style;\n    }	0
30282477	30281390	Server side not reading message correctly	data = System.Text.Encoding.ASCII.GetString(bytes, 0, i);\n      Console.WriteLine(StripExtended(data));        \n\n\n\n        static string StripExtended(string arg)\n        {\n            StringBuilder buffer = new StringBuilder(arg.Length); //Max length\n            foreach(char ch in arg)\n            {\n                UInt16 num = Convert.ToUInt16(ch);//In .NET, chars are UTF-16\n                //The basic characters have the same code points as ASCII, and the extended characters are bigger\n                if((num >= 32u) && (num <= 126u)) buffer.Append(ch);\n            }\n            return buffer.ToString();\n        }\n    }\n}	0
1537453	1537270	Generic method to set Control values	static class ControlAssign\n{\n\n    public static void Assign(Control target, object source, PropertyInfo prop)\n    {\n        Setters[prop.PropertyType](prop, source, target);\n    }\n\n    static ControlAssign()\n    {\n        Setters[typeof(string)] = (prop, src, target) =>\n        {\n            ((TextBox)target).Text =\n                (string)prop.GetValue(src, null);\n        };\n\n        Setters[typeof(bool?)] = (prop, src, target) =>\n        {\n            ((CheckBox)target).Checked =\n                (bool)prop.GetValue(src, null);\n        };\n\n        Setters[typeof(bool)] = (prop, src, target) =>\n        {\n            ((CheckBox)target).Checked =\n                (bool)prop.GetValue(src, null);\n        };\n    }\n\n    public delegate void Action<T, U, V>(T t, U u, V v);\n\n    readonly static Dictionary<Type, Action<PropertyInfo, object, Control>> Setters = new Dictionary<Type, Action<PropertyInfo, object, Control>>();\n}	0
3307178	3307100	String Formating in C#	var data = new List<string> {"A_1", "A_2", "A_B_1", "X_a_Z_14"};\n\nint trimPosition;\nfor (var i = 0; i < data.Count; i++)\n         if ((trimPosition = data[i].LastIndexOf('_')) > -1)\n            data[i] = data[i].Substring(0, trimPosition);	0
17040203	17040037	Getting a null exception as model in razor	public ActionResult Error()\n    {\n\n\n\n        return View();\n    }	0
23866141	23866005	How to put a button at center of column in stackpanel	txtblkLabel.VerticalAlignment = System.Windows.VerticalAlignment.Center;\n   txtblkLabel.HorizontalAlignment = System.Windows.HorizontalAlignment.Center;\n   txtblkLabel.TextAlignment = System.Windows.TextAlignment.Center;	0
21298505	21291709	Run many custom C# PowerShell cmdlet from one another custom cmdlet	pipeline = Runspace.DefaultRunspace.CreateNestedPipeline();	0
6766566	6766546	produce intersection and decomposition lists with two generic lists	var intersection = list1.Intersect(list2).ToList();\nvar list1Decomp = list1.Except(intersection).ToList();\nvar list2Decomp = list2.Except(intersection).ToList();	0
34559188	34559177	C# Add int numbers to a list while running a loop	var numbers = new List<int>();\nfor(int i=500; i<=2000000; i+=150)\n{\n    numbers.Add(i);\n}	0
13267883	13267657	adding a ListBoxItem in a ListBox in C#?	ListBoxItem itm = new ListBoxItem();\nitm.Content = "some text";\n\nlistbox.Items.Add(itm);	0
25783802	25783683	Reading XML from REST API	string response;\n        try\n        {\n            using (StreamReader streamIn = new StreamReader((webRequest.GetResponse()).GetResponseStream()))\n            {\n                response = streamIn.ReadToEnd();\n                streamIn.Close();\n            }\n        }finally\n        {webRequest.Abort();}\n\n       XDocument xDoc = XDocument.Parse(response);	0
5596383	5596298	.NET - How to compare performances between 2 blocks of code?	//initialise objects/vairables subject to memory measurement\n\n    long memUsageBefore = GC.GetTotalMemory(true); \n\n    //do something with some measured object\n\n    long memUsageAftere  = GC.GetTotalMemory(true); \n\n    // make it ineligible for garbage collection from the start of the current routine to the point where this method is called. \n    GC.KeepAlive(measuredObject);	0
22223657	22223085	How to change Dateformat	var worker = new BackgroundWorker();\n        worker.DoWork += (o, ea) =>\n        {\n        //and here would be system format\n         };\n        worker.RunWorkerCompleted += (o, ea) =>\n        {\n\n        };	0
26623201	26623135	Trying to get a valid integer from keyboard input	//Assign to temp_int first:\nint.TryParse(Console.ReadLine(), out temp_int);\nwhile (temp_int < 1)\n{\n    Console.WriteLine("Not a valid number....try again");\n    int.TryParse(Console.ReadLine(), out temp_int);\n}	0
3643789	3643753	best way to convert collection to string	var sb = new Text.StringBuilder;\nforeach (var item in requestParameters)\n{\n    sb.AppendFormat("{0}{1}", item.Key, item.Value);\n}\nvar parameters = sb.ToString();	0
14034094	14034019	How to make mapping between List<string> and a string?	Mapper.CreateMap<MyViewModel, MyModel>()\n      .ForMember(d => d.ContentLinks, opt => opt.MapFrom(s => s.ContentLink));	0
9617977	9617490	how to expose a c# class as a com objects interface?	public class PortWrapper {\n   public int ReceivePort {\n      get { return portRecv; }\n      set { \n         if (value == portRecv) return;\n         if (value < 256 || value > 65535) throw new ArgumentOutOfRangeException();\n         portRecv = value;\n         setupReceiver();\n      }\n   }\n   // etc..\n\n   private int portRecv=10101;\n}	0
19264130	18742895	How can I disable image loading in Awesomium?	public class ResourceInterceptor : IResourceInterceptor\n{\n    public bool NoImages { get; set; }\n\n    private static string[] _imagesFileTypes = { ".png", ".jpg", ".jpeg", ".gif", ".bmp" };\n\n    public ResourceResponse OnRequest(ResourceRequest request)\n    {\n        string ext = System.IO.Path.GetExtension(request.Url.ToString()).ToLower();\n\n        if (NoImages && _imagesFileTypes.Contains(ext))\n        {\n            request.Cancel();\n        }\n\n        return null;\n    }\n\n    public bool OnFilterNavigation(NavigationRequest request)\n    {\n        return false;\n    }\n}\n\n\n...\n\nResourceInterceptor ResInt = new ResourceInterceptor();\nWebCore.ResourceInterceptor = ResInt;	0
30126132	30124471	xl.XmlMap not a valid context C#	xl.XmlMap map;\n    wb.XmlImport(path, out map, Type.Missing, ws.Range["A1"]);	0
30530556	30528301	grouping data in ObservableCollection<T>	public async Task AddData(Data data)\n    {\n        var id = data.ID;\n        Group newGroup = new Group(id);\n        bool checkIfExists = false;\n\n        foreach (Group group in _groups)\n        {\n            if (group.ID == newGroup.ID)\n            {\n                checkIfExists = true;\n                break;\n            }               \n        }\n\n        if (checkIfExists)\n        {\n            foreach (Group group in _groups)\n            {\n                if (group.ID == id)\n                {\n                    group.DataGroup.Add(data);\n                }\n            }       \n        }\n        else\n        {\n            newGroup.DataGroup.Add(data);\n            _groups.Add(newGroup);\n        }\n\n        await saveDataAsync();               \n    }	0
9993221	9993172	Remove objects with a duplicate property from List	fooArray.GroupBy(x => x.Id).Select(x => x.First());	0
10846508	10844627	XNA: A list that I update every frame seems to lose its first few entries	public class LogList<T> : List<T>\n    {\n        public LogList()\n            : base()\n        {\n            Debug.WriteLine("LogList- Construction");\n        }\n\n        public new void Add(T item)\n        {\n            Debug.WriteLine("LogList - Add");\n            base.Add(item);\n        }\n\n        public new void Remove(T item)\n        {\n            Debug.WriteLine("LogList - Remove");\n            base.Remove(item);\n        }\n\n        public new void RemoveAt(int index)\n        {\n            Debug.WriteLine("LogLost - RemoveAt");\n            base.RemoveAt(index);\n        }\n\n        public new void Clear()\n        {\n            Debug.WriteLine("LogList - Clear");\n            base.Clear();\n        }\n    }	0
16278323	16278248	use collection initializer with insert statement	public bool InsertUsername(string username)\n{\n    string SQL = "Insert into [Users](Username, InsertDateTime) Values(@Username, datetime('now'));";\n    var pars = new List<SQLiteParameter> {new SQLiteParameter("@Username", username)};\n    return SQLiteUsernameDatabase.ExecuteNonQuery(SQL, pars);\n}	0
29409014	29408823	How to update value in dictionary if second parameter of it is list of objects C#	// find list in dictionary\nList<Account> acctList = dictionaries[keyString];\n// search account in list\nAcount account = acctList.FirstOrDefault(a => a.AccountName = acctName);\nif(account == null) // some error handling here\n// modify account\naccout.Balance -= 5;	0
335204	335135	Creating XML with namespaces and schemas from an XElement	// The http://www.adventure-works.com namespace is forced to be the default namespace.\nXNamespace aw = "http://www.adventure-works.com";\nXNamespace fc = "www.fourthcoffee.com";\nXElement root = new XElement(aw + "Root",\n    new XAttribute("xmlns", "http://www.adventure-works.com"),\n///////////  I say, check out this line.\n    new XAttribute(XNamespace.Xmlns + "fc", "www.fourthcoffee.com"),\n///////////\n    new XElement(fc + "Child",\n        new XElement(aw + "DifferentChild", "other content")\n    ),\n    new XElement(aw + "Child2", "c2 content"),\n    new XElement(fc + "Child3", "c3 content")\n);\nConsole.WriteLine(root);	0
4817576	4817511	declare an object c#	object myObject = null;\n\n    if(myObject != null)\n    {\n     // your code\n    }	0
19483460	19482777	Automapper, add number of days to destination DateTime property	public class Source\n{\n    public int ExtendedDurationInWeeks { get; set; }\n}    \n\npublic class Destination\n{\n    public DateTime ExpirationDate { get; set; }\n\n    public Destination()\n    {\n        ExpirationDate = DateTime.Now.Date;\n    }\n}\n\nvar source = new Source{ ExtendedDurationInWeeks = 2 };\nvar destination = new Destination {ExpirationDate = DateTime.Now.Date};\n\nMapper.CreateMap<Source, Destination>()\n      .AfterMap((s,d) => d.ExpirationDate = \n                        d.ExpirationDate.AddDays(s.ExtendedDurationInWeeks * 7));\n\ndestination = Mapper.Map(source, destination);	0
20523901	20522873	Iterate through Lists in a site and load results in a DropDownList	class MyListsOfLists\n{\n    public ObjectLists AllLists { get; set; }\n}\n\nclass ObjectLists\n{\n    public List<Adult> Adults { get; set; }\n    public List<Child> Children { get; set; }\n    public List<Dog> Dogs { get; set; }\n    public List<Car> Cars { get; set; }\n    public List<House> Houses { get; set; }\n}\n\n\nclass Adult\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n    public DateTime DOB { get; set; }\n}\n\n\nclass Child\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n    public DateTime DOB { get; set; }\n}\n\n\nclass Dog\n{\n        public int ID { get; set; }\n        public string Name { get; set; }\n        public DateTime DOB { get; set; }\n}\n\nclass Car\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n    public DateTime ModelYear { get; set; }\n}\n\nclass House\n{\n    public int ID { get; set; }\n    public string Name { get; set; }\n    public DateTime Built { get; set; }\n}	0
33113470	33047990	Print high quality Tiff documents from picturebox C#	myBmp = new Bitmap(myImg, pictureBox1.Width, pictureBox1.Height); \n    pictureBox1.Image = myBmp;	0
10979458	10896732	Building a tree out of items list	private void RecursiveBuilder(ref Item i, IEnumerable<Item> li)\n{\n    var item = i;\n    i.SubItems = (from n in li where n.ParentId == item.Id select n).ToList();\n    i.SubItems.ForEach(f => RecursiveBuilder(ref f, li));\n}	0
18822910	18822770	Change picture box picture	pbIndicator.Image = Resources.indicator_green;	0
23106314	23106226	How to determine the no of enum items declared in c#	enum MyEnum \n{\n  foo = 1,\n  bar = 2\n}\n\nvar noOfEnums = Enum.GetNames(typeof(MyEnum)).Length;	0
8123748	8123319	Add node and childnodes to XML File	XmlSerializer serializer = new XmlSerializer(typeof(yourObject));\nTextWriter streamWriter = new StreamWriter(filename);\nserializer.Serialize(streamWriter, yourObject);\nstreamWriter.Close();	0
24303934	24303264	Open file by part of his name	var directoryInfo = new DirectoryInfo(@"c:\temp");\nvar latestFile = directoryInfo.GetFiles()\n                              .Where(f => f.Name.StartsWith("12345_"))\n                              .OrderByDescending(f => f.CreationTime)\n                              .FirstOrDefault();	0
1160624	1160609	.NET testing a string for numeric value	double.TryParse	0
33379498	33376011	How to Convert Binary file data to a physical type with a given MIME Type	// fileContents is the binary file being downloaded; I didn't need to use the MIME Types\n        MemoryStream ms = new MemoryStream(fileContents);\n        //write to file\n        FileStream file = new FileStream(filePath, FileMode.Create, FileAccess.Write);\n        ms.WriteTo(file);\n        file.Close();\n        ms.Close();	0
24606420	24606399	How do i get the value of first index in a returned List of array	account.ForEach(s => listBoxFirstname.Items.Add(s[0]));	0
2682478	2682136	C# WinForms ErrorProvider Control	private class ErrorTracker {\n  private HashSet<Control> mErrors = new HashSet<Control>();\n  private ErrorProvider mProvider;\n\n  public ErrorTracker(ErrorProvider provider) { \n    mProvider = provider; \n  }\n  public void SetError(Control ctl, string text) {\n    if (string.IsNullOrEmpty(text)) mErrors.Remove(ctl);\n    else if (!mErrors.Contains(ctl)) mErrors.Add(ctl);\n    mProvider.SetError(ctl, text);\n  }\n  public int Count { get { return mErrors.Count; } }\n}	0
21766447	21765995	C# get index of bit	public static void Main()\n{\n    uint data = 0x3E;\n    uint firstMask = 1;\n    uint lastMask = 0x80000000;\n    int? first = null;\n    int? last = null;\n\n    for (int i=0; i < 32; i++) {\n        if ((firstMask & data) > 0 && first == null)\n        {\n            first = i;\n        }\n        if ((lastMask & data) != 0 && last == null)\n        {\n            last = i;\n        }\n        firstMask = firstMask << 1;\n        lastMask = lastMask >> 1;\n    }\n    last = 31-last;\n\n\n    Console.WriteLine(first);\n    Console.WriteLine(last);\n}	0
9110140	9109935	Wrong display format for .doc	p1.InnerHtml += "<p>" + Doc.Paragraphs[i].Range.Text + "</p>";	0
30799234	30799107	Change the Console.Foregroundcolor from a string	Console.WriteLine("Name a color");\n        string color = Console.ReadLine();\n\n        ConsoleColor consoleColor = ConsoleColor.White;\n        try\n        {\n            consoleColor = (ConsoleColor)Enum.Parse(typeof(ConsoleColor), color, true);\n        }\n        catch (Exception)\n        {\n            //Invalid color\n        }\n\n        Console.ForegroundColor = consoleColor ;	0
29634816	29632049	Is There A Better Way to Add Entropy to Array of Ints?	public static int[] GetArray(int sum, int n)\n{\n    if(sum < n)\n        throw new ArgumentException("sum is lower than n");\n    Random rnd = new Random();\n\n    // reserve 1 for each of the elements\n    sum -= n;\n\n    // generate random weights for every element in sum\n    int[] w = new int[n];\n    int sw = 0;             \n    for (int i = 0; i < n; i++)\n    {\n        w[i] = rnd.Next(0, 100);\n        sw += w[i];\n    }\n\n    // generate element values based on their weights\n    int[] result = new int[n];\n    int tsum = 0;\n    int psum = 0;\n    for (int i = 0; i < n; i++)\n    {\n        tsum += w[i] * sum;\n        result[i] = tsum / sw - psum;\n        psum += result[i];\n    }\n\n    // restore reserved ones\n    for (int i = 0; i < n; i++)\n        result[i]++;\n\n    return result;\n}	0
10244942	10243153	Press Enter Key in Selenium RC with C#	import org.openqa.selenium.Keys;\n\n//...\n\n// this sends an Enter to the element\nselenium.type("locator", Keys.ENTER);\n\n// or even this - this sends the "Any text" and then confirms it with Enter\nselenium.type("locator", "Any text" + Keys.ENTER);	0
4092810	4092794	C# integer masking into byte array	this._data[1] = (byte)(Distance >> 8);	0
22968925	22693481	How to CREATE Store Procedures in MySql via C# code	MySqlScript script = new MySqlScript(conn, query);\nscript.Delimiter = "$$";\nscript.Execute();	0
31567647	31567336	Constraining X and Y Draggable Area	float maxDragX = 1000;\n    float maxDragY = 700;\n\n    Vector3 mousePosition = new Vector3(eventData.position.x, eventData.position.y, distance);\n\n    transform.position = mousePosition;                                 // set object coordinates to mouse coordinates\n\n    if(transform.parent.gameObject == partsPanel)\n    {\n        transform.SetParent(dragLayer.transform);                       // pop object to draglayer to move object out of partsPanel\n    }\n\n    if(transform.parent.gameObject == buildBoard)\n    {\n        // Constrain drag to boundaries of buildBoard Code\n        if(transform.position.x >= maxDragX)\n            transform.position = new Vector3(maxDragX, mousePosition.y, distance);\n\n        if(transform.position.y >= maxDragY)\n            transform.position = new Vector3(mousePosition.x, maxDragY, distance);\n    }	0
2119774	2119510	Change Desktop Wallpaper using a Jpeg file	public class ChangeWallpaper\n{\n    [DllImport("user32.dll", CharSet = CharSet.Auto)]\n    static extern int SystemParametersInfo(int uAction, int uParam, string lpvParam, int fuWinIni);\n\n    public static void Main()\n    {\n        Bitmap bm = new Bitmap(Image.FromFile("pic.jpg"));\n        bm.Save("pic.bmp", ImageFormat.Bmp);\n        SystemParametersInfo(20, 0, "pic.bmp", 0x01 | 0x02);\n    }\n}	0
26160632	26160503	Creating dictionaries with pre-defined keys C#	public Dictionary<string, string> NewEntryDictionary()\n{\n    return Enum.GetNames(typeof(Suits)).ToDictionary(name => name, name => "");\n}	0
8527245	8527188	How to join 2 tables in LINQ to Entity?	var db = DatabaseContext.FromContext();\nvar result = (from a in db.TableA \n              join b in db.TableB on a.ID equals b.TableAID \n              select new {\n                  AID = a.ID, \n                  AName = a.Name, \n                  AType = a.Type, \n                  BName = b.Name}).ToList();	0
16017876	16017587	How can I make Ctrl+M an event that brings up a form?	private void OnKeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e) \nif (((Control.ModifierKeys & Keys.Control) == Keys.Control) \n    && (e.KeyChar == 'M'|| e.KeyChar == 'm'))\n{\n        mf.Show();\n}	0
12596511	12596321	How make lambda where on list of list?	var filteredList = list\n  .Select(\n    x => new firstClass {\n      Id = x.Id,\n      Elements = x.Elements.Where(y => y.Is).ToList()\n    }\n  )\n  .Where(x => x.Elements.Count > 0);	0
11111523	11066004	C# Linear Discriminant Analysis with Alglib	static public double[,] Test()\n    {\n        // This example is for points in 3D.\n        // The forth variable is the class label. In this case 2 classes: 0 and 1.\n        double[,] xy = new double[,]\n        {\n        { 4,2,1, 0 }, { 2,4,2, 0 }, { 2,3,3, 0 }, { 3,6,4, 0 }, { 4,4,5, 0 },\n        { 9,10,10, 1 }, { 6,8,11, 1 }, { 9,5,12, 1 }, { 8,7,9, 1 }, { 10,8,10, 1 }\n        };\n\n        int NPoints = 10;\n        int NVars = 3; // 1 for 1 dimension, 2 for 2D and so on...\n        int NClasses = 2;\n\n        int info = 0;\n        double[,] w = new double[0, 0];\n\n        alglib.lda.fisherldan(xy, NPoints, NVars, NClasses, ref info, ref w);\n\n        return w; // The projection vector/s.\n    }	0
21647507	21647363	how to display data from multiple tables to dataGridView	using(MySqlConnection connection = new MySqlConnection(MyConnectionString))\nusing(MySqlCommand cmd = connection.CreateCommand())\n{\n    connection.Open();\n    cmd.CommandText = "SELECT pb.Id, pb.Name, pb.MobileNo, e.email FROM phonebook pb INNER JOIN email e ON e.Id= pb.Id";\n    MySqlDataAdapter adap = new MySqlDataAdapter(cmd);\n    DataSet ds = new DataSet();\n    adap.Fill(ds);\n    dataGridView1.DataSource = ds.Tables[0].DefaultView;\n}	0
1722061	1721997	How can I place element to position with Silverlight?	Rectangle rectangle = new Rectangle() { Width = e.EndPoint.X - e.StartPoint.X, Height = e.EndPoint.Y - e.StartPoint.Y, Fill = new SolidColorBrush(Colors.Purple) };\n Canvas.SetLeft(rectangle, e.StartPoint.X);\n Canvas.SetTop(rectangle, e.StartPoint.Y);\n PictureCanvas.Children.Add(rectangle);	0
26575915	26575883	Use 2(or more) Database in one asp application and switch connection string	web.config	0
25441428	25437724	Writing a simple OData client: how to query service?	// Create a service context object\n// "NorthwindEntities" is the name of the class in the generated service reference that derives DataServiceContext\n// The URI in should be the same URI you used to add the service reference\nvar context = new NorthwindEntities(new Uri("http://services.odata.org/Northwind/Northwind.svc/"));\n\n// As Alphabetical_list_of_products is an entity set, it can be directly called from the context\n// Call Execute() finally to send the request to the OData service and materialize the response got to "products"\nvar products = context.Alphabetical_list_of_products.Execute();\n\n// Iterate through all the products and print "ProductName", which is the name of a property on "Alphabetical_list_of_product" entity\nforeach (var product in products)\n{\n    Console.WriteLine(product.ProductName);\n}	0
5293720	5293065	Updating list object based on key - LINQ	memObjects.ForEach(x => x.ModifiedAt.AddSeconds(memObjects.Count(y => y.Serial == x.Serial && y.ErrorCode == x.ErrorCode)));	0
6315626	6315572	Limiting the scope of a NamedPipeServerStream	[DllImport("kernel32.dll",SetLastError=true)]\nstatic extern int ProcessIdToSessionId(int pid, ref int session);	0
8982997	8982654	Disable all anchor tags on asp.net page using c#	protected void Page_Load(..)\n{\n    String strScript = "$('a').click(function(e) { e.preventDefault(); });";\n\n    if(condition)\n    {\n        Page.ClientScript.RegisterStartupScript(this.GetType(), "disableAnchor", strScript, true);\n    }\n}	0
24647540	24647478	Removing HTML from a string	var text = "Hello friend <br> How are you? <h1> from me </h1>";\nvar newText = text.replace(/(<([^>]+)>)/ig, "");	0
23109359	23108664	Using linq to retrieve differences between two lists with duplicates	var al = Duplicate1.ToLookup(x => x);\nvar bl = Duplicate2.ToLookup(x => x);\n\nvar result = al.Join(bl,  agrp        => agrp.Key, \n                                bgrp  => bgrp.Key,\n                         (agrp, bgrp) => agrp.Count() > bgrp.Count() ?\n                                         agrp.Take(agrp.Count() - bgrp.Count()) :\n                                         bgrp.Take(bgrp.Count() - agrp.Count()))\n                .SelectMany(x => x);	0
27176039	27174940	Assigning identifiers to elements through a binding	var childControl = this.ListView.Children.OfType<Button>().Single(f => f.Content == "Blah");	0
16442553	16442502	How to get child control?	var picBox = TabControl1.SelectedTab.Controls.OfType<PictureBox>().First();	0
2873497	2873332	Input string was not in a correct format?	byte[] byt = Encoding.UTF8.GetBytes(textbox1.Text);	0
25383769	25383736	how to get the last three elements from the string array in c#	string[] arrstr = str.Reverse().Take(3).Reverse().ToArray();	0
24733319	24733077	In Manipulating the Windows file system I'm getting an exception while moving file from one directory to other	File.Move(@"C:\Users\kireett\Desktop\mydata\1.html", @"C:\Users\kireett\Desktop\Data sheet\2.html");	0
28394863	28394748	How OnNavigatedTo() invoke only once?	protected  override void OnNavigatedTo(NavigationEventArgs e)\n{  \n    if (e.NavigationMode != NavigationMode.Back)\n    {\n        // add items to your collection\n    }\n}	0
27281798	27258090	How to insert a model in ef 6 with a many to many relationship	public HttpResponseMessage Post(JobRequest request) \n{\n    // ... model validation, other checks\n\n    // create job object\n    var job = new Job { Name = request.Name, Candidates = new Collection<Candidate>() };\n\n    // associate existing candidates to the job\n    foreach(var candidate in request.Candidates) {\n        var c = new Candidate { Id = candidate.Id};\n        context.Candidates.Attach(c);   // without this, EF will try to create new Candidate\n        job.Candidates.Add(c);    // associate the existing candidate with the job\n    }\n\n    context.Jobs.Add(job);      // add the job\n    context.SaveChanges();      // save\n\n    // ... handle errors, return status codes etc.\n\n}	0
18732112	18732092	how to add space between radiobuttonlist which is created dynamically in code behind	ddlst1.Items[k].Attributes.CssStyle.Add("margin-right:5px;")	0
12195751	12195729	How to copy int array value into byte array? only copy the value in C#	streambit = arrayint.Select(i => (byte)i).ToArray();	0
21766099	21764116	How can I eagerly fetch data on this query?	menuItems = UnitOfWork.CurrentSession\n.QueryOver<TopMenuItem>()\n.JoinAlias(i => i.Action, () => ua, JoinType.LeftOuterJoin)\n.JoinAlias(() => ua.Roles, () => ro, JoinType.LeftOuterJoin)\n.List();	0
4680185	4680128	C#: split a string with delimiters but keep the delimiters in the result	string input = "plum-pear";\nstring pattern = "(-)";\n\nstring[] substrings = Regex.Split(input, pattern);    // Split on hyphens\nforeach (string match in substrings)\n{\n   Console.WriteLine("'{0}'", match);\n}\n// The method writes the following to the console:\n//    'plum'\n//    '-'\n//    'pear'	0
18206058	18205560	Do I need to explicitly dispose SqlDataAdapter?	using (SqlConnection con = new SqlConnection(connstring))\nusing (SqlCommand com = new SqlCommand())\nusing (SqlDataAdapter da = new SqlDataAdapter())\n{\n   com.Connection = con;\n   //etc..\n}	0
25659077	25658533	how to keep space in flow layout panel	Button btn = new Button();\n btn.Name = btn.Text = string.Format("Button{0}", i + 1);\n btn.Margin = new Padding(5, 5, 5, 5);\n flowLayoutPanel1.Controls.Add(btn);	0
16392377	16392337	Explanation for having Regex Match Group no error	public Group this[int groupnum] { get; }	0
11818752	11818664	Send Texture2d object to function	commonImageLoader( ref bkgrSource[0], ref bkgrBANK[0] ); \n\nprivate void commonImageLoader(ref string source, ref Texture2D destination ) {\n    if ( !string.IsNullOrEmpty( source ) ) {\n        fileName = source;\n        using ( fileStream = new FileStream( @fileName, FileMode.Open ) ) {\n        destination = Texture2D.FromStream( GraphicsDevice, fileStream );\n        }\n    }\n}	0
27590049	27561409	Export in Crystal report to PDF only 75 files are exported out of 500 files using c#	Protected Sub Page_Unload(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Unload\n    cr.Close()\n    cr.Dispose()\nEnd Sub	0
10222094	10211495	DNS api for Windows Server 2008 R2 DNS server higher-level than WMI?	WMI Delphi Code Creator	0
25929980	25927645	Filter Grid from a public property	protected void Af_FilterButtonClicked(object sender, EventArgs args)\n{    \n   if(!string.isNullOrWhiteSpace(jobFilter.SelectedCountry))\n   {\n     var data= YourDataSource.Where(c=> c.YourCountryField == jobFiler.SelectedCountry).ToList();\n     YourGrid.DataSource= data;\n     YourGrid.DataBind(); // or Rebind()\n   }\n}	0
26518722	26516230	How to setup service locator to test view models in MVVM	[SetUp]\n  public void RunBeforeAllFixtures()\n        {\n            ServiceLocator.SetLocatorProvider(() => SimpleIoc.Default);\n            _vm = new TestViewModel();\n\n        }	0
27036444	27033742	Remove duplicate from large lists efficiently?	list = list.Where((entry, i) => i == 0 || entry.Item1 != list[i - 1].Item1).ToList();	0
21187488	21147830	ITextSharp 5.4.5 How can I set an ATL to an image of a document I?m creating from scratch?	private static void Main(string[] args)\n    {\n        using (Document doc = new Document(PageSize.A4, 36, 36, 36, 36))\n        {\n            using (PdfWriter pw = PdfWriter.GetInstance(doc, new FileStream("c:\\ImageTest.pdf", FileMode.Create)))\n            {\n                pw.SetTagged();\n                pw.UserProperties = true;\n                doc.Open();\n                pw.PdfVersion = PdfWriter.VERSION_1_7;\n                Image img = Image.GetInstance(@"c:\images\WA.png");\n                img.SetAbsolutePosition(36, 592);\n                img.Alt = "Alt Text for Image!";\n                doc.Add(img);\n                doc.Close();\n            }\n        }\n    }	0
6324332	6324276	Wpf start in primary screen	using System;\nusing System.Windows;\nusing System.Windows.Forms;\n\nnamespace Foo\n{\n    public class WindowUtility\n    {\n        public static void MoveToMonitor(Window window, int monitorId, bool maximize)\n        {\n            Screen[] screens = Screen.AllScreens;\n\n            int screenId = monitorId - 1;\n\n            if (screens.Length > 1 && screenId < screens.Length)\n            {\n                var screen = screens[screenId];\n                var area = screen.WorkingArea;\n\n                if (maximize)\n                {\n                    window.Left = area.Left;\n                    window.Top = area.Top;\n                    window.Width = area.Width;\n                    window.Height = area.Height;\n                }\n                else\n                {\n                    window.Left = area.Left;\n                    window.Top = area.Top;\n                }\n            }\n        }\n    }\n}	0
12470691	12470667	C# setting a tooltip to a <asp:Label> or a <asp:Literal>	Label1.ToolTip = "Your text as tooltip";	0
26341282	26341083	Reading xml comment outside the tag	var doc = XDocument.Parse(docStr);\n var commentValue = doc.Nodes().OfType<XComment>().First().Value;	0
7515221	7515018	How to download data from an ASP.Net webpage to an Excel file?	void WriteToXls(string fromfilePath, string targetFileName)\n    {\n        if (!String.IsNullOrEmpty(fromfilePath)) \n        {\n            HttpResponse response = HttpContext.Current.Response;\n            response.Clear();\n            response.Charset = "utf-8";\n            response.ContentType = "text/xls";\n            response.AddHeader("content-disposition", string.Format("attachment; filename={0}", targetFileName));\n            response.BinaryWrite(File.ReadAllBytes(fromfilePath));\n            response.End();\n        }\n    }	0
6344812	6344774	Using String Split	variable.Split(new char[] { ',' }, 2)	0
13907088	13907022	When is a ReadOnly Variable allocated?	private readonly int readOnlyExample;\n\npublic YourClassConstructor()\n{\n    this.readOnlyExample = 10;\n}	0
3518887	3488811	How to add parameter for postgres enum types in C#	INSERT INTO tableName (Col) VALUES ( CAST(:p1 as "TestEnum") )	0
3193035	3141078	Scale text in a grid/viewbox upon pinching	{label name}.FontSize *= (double)e.NewSize.Height / (double)e.PreviousSize.Height;	0
25899151	25899034	Dynamic grid within a scrollviewer	Height="577"	0
7579972	7579936	How do i execute a process in C# that installs a printer driver?	var p = new System.Diagnostics.Process();\np.StartInfo = new System.Diagnostics.ProcessStartInfo { FileName = "yourfile.exe", UseShellExecute = true };\np.Start();	0
11020011	11019933	Scroll to the end of a Single-Line Textbox in C#	PathText.Focus();\n PathText.Select(PathText.Text.Length, 0);	0
5250096	5250060	Set pop up help of a function for Intelligence support in C#	/// <summary>This method does something funky.</summary>\npublic void Foo()\n{\n}	0
616699	545173	Sending fax with .NET	BLANK LINE\n [[TO=Fax Number or Email address]]\n [[SUBJECT=Whatever you want the subject to be]]	0
18241191	5758732	Playing a second SoundEffect after the first one has finished	public static void Update()\n        {\n            if (_sheduledSounds != null && _sheduledSounds.Count > 1)\n            {\n                if (_sheduledSounds.Peek().State == SoundState.Stopped)\n                {\n                    _sheduledSounds.Dequeue();\n                    _sheduledSounds.Peek().Play();\n                }\n            }\n        }	0
10139841	10137547	Finding objects which contains at least one element from subset using RavenDB and LINQ	string[] tags = new[] { "a", "b" };\nstring queryRange = "(" + string.Join(" OR ", tags) + ")";\n\nvar res = session.Advanced.LuceneQuery<Question>()\n               .Where("Tags:" + queryRange).ToList();	0
21077809	21077783	Parsing StringBuilder HTML to WebBrowser control using C#	private void button1_Click(object sender, EventArgs e)\n{\n    webBrowser1.DocumentText = htmlMessageBody(yourdataGridView).ToString();\n}	0
14295569	14295291	Sequence of animations in WPF with BeginAnimation	var storyboard = new Storyboard();\nvar totalDuration = TimeSpan.Zero;\n\nfor (...)\n{\n    var rotation = new AxisAngleRotation3D(axis, angle);\n    var transform = new RotateTransform3D(rotation, new Point3D(0, 0, 0));\n    var duration = TimeSpan.FromMilliseconds(370);\n    var animation = new DoubleAnimation(0, angle, duration);\n\n    animation.BeginTime = totalDuration;\n    totalDuration += duration;\n\n    Storyboard.SetTarget(animation, rotation);\n    Storyboard.SetTargetProperty(animation, new PropertyPath(AxisAngleRotation3D.AngleProperty));\n\n    storyboard.Children.Add(animation);\n}\n\nstoryboard.Begin();	0
9294744	9294571	Default property for a class when deserialize XML to an object	[DataMember]\n[XMLText]\n  public string Identifier { get; set; }	0
14979030	14978954	Adding a button onto each row of a table	TableCell cell = new TableCell();\ncell.Controls.Add(deleteButton);\nr.Cells.Add(cell);	0
25448521	25447953	Solution with several project namespaces	MyProduct.DataLayer\nMyProduct.UI\nMyProduct.Tools\nMyProduct	0
2262229	2262204	How do I assert that a character belongs to a list of expected values?	Assert.IsTrue( ((IList)expected).Contains(actual));	0
32001714	31929485	Entity Framework Multiple Result Sets, Azure Connection Resiliency and Command Interception	var paramId = new SqlParameter\n{\n    ParameterName = "id",\n    SqlDbType = SqlDbType.Xml,\n    Direction = ParameterDirection.Input,\n    Value = 1\n};\n\nvar paramXmlResult = new SqlParameter\n{\n    ParameterName = "XmlResult",\n    SqlDbType = SqlDbType.Xml,\n    Direction = ParameterDirection.Output\n};\n\ndb.Database.SqlQuery<XElement>(\n    "EXEC [dbo].[GetDataAsXml] @id, @XmlResult OUT", \n    paramId, paramXmlResult).ToList();\n\n\nXElement xmlResult = XElement.Parse(paramXmlResult.Value.ToString());\n\n//FromXElement is an Extension method that deserializes XML into a Type (like MyData)\nMyData data = xmlResult.FromXElement<MyData>();	0
4257197	4257075	How to change property of every control in application	this.txtField.DataBindings.Add(\n    new System.Windows.Forms.Binding("Multiline", \n         global::ProjectNamespace.Properties.Settings.Default, \n         "BoolianSettingInConfigFile", \n         true, \n         System.Windows.Forms.DataSourceUpdateMode.OnPropertyChanged));	0
4526616	4525332	How to open a Hyperlink in WebBrowser control in windows phone 7?	Navigate()	0
13719883	13719614	Generate a pdf file and send after querying database for a pass mark	public FileStreamResult DownloadPDF()\n{\n        MemoryStream workStream = new MemoryStream();\n\n        using(Document document = new Document())\n        {\n            PdfWriter.GetInstance(document, workStream).CloseStream = false;\n\n            document.Open();\n\n            document.SetPageSize(PageSize.LETTER);\n            document.SetMargins(12, 12, 8, 7);\n            document.NewPage();\n\n            // Create a new Paragraph object with the text, "Hello, World!"\n            var welcomeParagraph = new Paragraph("Hello, World!");\n\n            // Add the Paragraph object to the document\n            document.Add(welcomeParagraph);\n\n            // This is where your data would go\n\n            document.Close();\n        }\n        workStream.Position = 0;\n\n        FileStreamResult fileResult = new FileStreamResult(workStream, "application/pdf");\n        fileResult.FileDownloadName = "test.pdf";\n\n        return fileResult;\n    }	0
1769914	1769886	How to code a truly generic tree using Generics	class Node<T, TChild> {...}\n\nNode<Document, Node<Paragraph, Node<Line, Word>>>	0
32546411	32545897	Accessing objects/rows created in ASP.NET from Javascript	var table = document.getElementById('mTable'); \n// will return you a reference to the table object on the page	0
171668	171664	How to turn these 3 methods into one using C# generics?	public T Evaluate<T>(T x, T y) {\n      switch (Operation)\n      {\n        case BinaryOp.Add:\n            return Operator.Add(x, y);\n        case BinaryOp.Subtract:\n            return Operator.Subtract(x, y);\n     ... etc	0
16847014	16837207	Build a list of criterias of optional filters for retrieving records nhibernate c#	var status = queryParams.FirstOrDefault(q => q.Key == "status").Value;\n        var entity = queryParams.FirstOrDefault(q => q.Key == "entity").Value;\n        var start = queryParams.FirstOrDefault(q => q.Key == "start").Value;\n\n        if(!string.IsNullOrEmpty(status))\n        {\n            query.Where(r => r.RowStatus == Convert.ToInt32(status));\n        }\n        if (!string.IsNullOrEmpty(entity))\n        {\n            query.Where(r => r.EntityType == entity);\n        }\n\n        //Ensure that this should be the last filter criteria to be applied\n        if (!string.IsNullOrEmpty(start))\n        {\n            query.Skip(Convert.ToInt32(start));\n        }\n\n        var count = query.RowCount();\n\n        var results = query.Take(apiUser.ApiLimit).List().Select(c => _cryptography.Decrypt(c.Json)).ToList();	0
26987932	26965197	Make Changes to a TFS Work Item as a specific user	public void Impersonation(Uri serverUri,string userToImpersonate)\n{\n    // Read out the identity of the user we want to impersonate\n    TeamFoundationIdentity identity = ims.ReadIdentity(IdentitySearchFactor.AccountName, \n        userToImpersonate,\n        MembershipQuery.None, \n        ReadIdentityOptions.None);\n\n    tfs_impersonated = new TfsTeamProjectCollection(serverUri, identity.Descriptor);\n\n    GetAuthenticatedIdentity(tfs_impersonated);\n\n    // Use this tfs_impersonated object to communicate to TFS as the other users.\n}	0
29046726	29046715	extract values from DataTable with single row	private void GetUser(string userId)\n{\n    dbr.SelectString = "select name, gender,  address, contactno from userInfo where id = = '" + userId + "' --"; // return single row\n    DataTable dt = dbr.GetTable();\n    if (dt.Rows.Count > 0) \n    {\n    DataRow row = dt.Rows[0];\n\n    lbl_name = row["name"].ToString();\n    lbl_gender = row["gender"].ToString();\n    lbl_contact = row["contactno"].ToString();\n    }\n}	0
2111847	2111747	How to validate xml code file though .NET? + How would I do it if I use XML serialization?	using (FileStream stream = File.OpenRead(xsdFilepath))\n{\n    XmlReaderSettings settings = new XmlReaderSettings();\n\n    XmlSchema schema = XmlSchema.Read(stream, OnXsdSyntaxError);\n    settings.ValidationType = ValidationType.Schema;\n    settings.Schemas.Add(schema);\n    settings.ValidationEventHandler += OnXmlSyntaxError;\n\n    using (XmlReader validator = XmlReader.Create(xmlPath, settings))\n    {\n        // Validate the entire xml file\n        while (validator.Read()) ;\n    }\n}	0
33713222	33712884	How to get transformed value of key from Web.config	.release	0
9454616	9454573	linq-to-sql conditional read	var TheOutput = (from x in MyDC.MyTable\n                 where.....\n                 let id = (from a in MyDC.MyOtherTable\n                                where....\n                                select a.ElementID).SingleOrDefault()\n                 select new MyModel()\n                 {\n                    MyPropID = id,\n                    MyPropData = (from a in MyDC.MyOtherTable\n                                  where id != null && a.ElementID == id\n                                  select a.ElementData).SingleOrDefault()\n                 }	0
24418794	24141715	How to add a listviewwebpart by code	SomePage.aspx?ListId=GUID	0
26057448	26057090	How to add and call additional Get Method in ASP.net WebAPI Project	routes.MapHttpRoute(\n    name: "ActionApi",\n    routeTemplate: "api/{controller}/{action}/{id}",\n    defaults: new { id = RouteParameter.Optional }\n);	0
18978576	18978316	Microsoft Server 2008 R2 not writing to text file from task scheduler	string filepath = Path.Combine(System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location),"NLog.txt");	0
21816173	21816043	How to find the type of derived class without multiple "is" statements?	private abstract class Base1\n    {\n\n    }\n\n    private class Extend1 : Base1\n    {\n\n    }\n\n        Base1 whatTypeAmI = new Extend1();\n        var t = whatTypeAmI.GetType();\n\n        if (t == typeof(Extend1))\n            {\n                //do work\n                Console.WriteLine("hello extend1");\n            }\n        else {\n                Console.WriteLine("I don't know what type I am");\n            }\n        }	0
18618062	18617750	Looping in RadGrid	foreach (Telerik.WinControls.UI.GridViewRowInfo row in RadGrid.Rows)\n{\n    foreach (Telerik.WinControls.UI.GridViewCellInfo cell in row.Cells)        \n    {\n\n    }\n}	0
6293266	6293051	multiview controls after postback	protected override void  OnInit(EventArgs e)\n    {\n        View view1 = new View();\n        View view2 = new View();\n        View view3 = new View();\n        Label l1 = new Label();\n        Label l2 = new Label();\n        Label l3 = new Label();\n\n        l1.Text = "1";\n        l2.Text = "2";\n        l3.Text = "3";\n\n        view1.Controls.Add(l1);\n        view2.Controls.Add(l2);\n        view3.Controls.Add(l3);\n        MultiView1.Views.Add(view1);\n        MultiView1.Views.Add(view2);\n        MultiView1.Views.Add(view3);\n        MultiView1.ActiveViewIndex = 0;\n\n        base.OnInit();\n    }\n\n\n    protected void Page_Load(object sender, EventArgs e)\n    {\n    }\n\n    protected void Button2_Click(object sender, EventArgs e)\n    {\n        MultiView1.ActiveViewIndex++;\n    }\n\n    protected void Button1_Click(object sender, EventArgs e)\n    {\n        MultiView1.ActiveViewIndex--;\n    }	0
3257110	3257038	C#, ASP.NET MVC / MVC2: Add wildcard route for specific controller - help building route	routes.MapRoute(\n"Store", // Route name\n"my-store/{val}/{id}/{id2}", // URL with parameters\nnew { controller = "Store", action = "Index", val = "", id = UrlParameter.Optional, id2 = UrlParameter.Optional }	0
28103922	28103686	Outlook opens the task in a modal window after I opened this task in a modal window from the application	email.Close();\nGC.WaitForPendingFinalizers();\nGC.Collect();\nGC.WaitForPendingFinalizers();\nGC.Collect();	0
12514232	12514167	How can i open files of different type with different algorithms in OpenFile dialog?	var dialog = new OpenFileDialog();\n\nif (dialog.ShowDialog() == DialogResult.OK)\n{\n    var extension = Path.GetExtension(dialog.FileName);\n\n    // do what you need\n}	0
8784214	8783987	How to let the user be able to change his answer to one of the questions in the quiz?	// Create Answer object to save values\n Answer a = new Answer();\n a.QuestionID = dr["QuestionOrder"].ToString();\n a.CorrectAnswer = dr["CorrectAnswer"].ToString();\n a.UserAnswer = answerDropDownList.SelectedValue.ToString();\n\n ArrayList al = (ArrayList)Session["AnswerList"];\n var oldAnswer = al.ToArray().Where(ans => (ans as Answer).QuestionID == a.QuestionID);\n if (oldAnswer.Count() != 0)\n {\n      a = oldAnswer.FirstOrDefault() as Answer;\n      a.CorrectAnswer = dr["CorrectAnswer"].ToString();\n      a.UserAnswer = answerDropDownList.SelectedValue.ToString();\n }\n else\n {\n      al.Add(a);\n }\n\n //Rest of your code	0
31903658	31903600	String formating issue	var str = @"0Raptr||""C:\Program Files (x86)\Raptr\raptrstub.exe"" --startup"\nvar match = Regex.Match(str, @"\|\|""(?<path>(?:\""|[^""])*)""");\nConsole.WriteLine(match.Groups["path"]);	0
33802236	33786339	Get a collection based on generic type	public class InMemoryDatabase\n  {\n      private Dictionary<Type, IEnumerable> _hashSets = new Dictionary<Type, IEnumerable>();\n\n      // Returns or creates a new HashSet for this type.\n      public HashSet<T> GetCollection<T>()\n      {\n          Type t = typeof(T);\n\n          if (!_hashSets.ContainsKey(t))\n          {\n              _hashSets[t] = new HashSet<T>();\n          }\n\n          return (_hashSets[t] as HashSet<T>);\n       }\n    }	0
2508373	2506046	CSharpCodeProvider 'cannot find metadata file' Compiling Plugin Code With Mono	System.dll\nSystem.Xml.dll	0
14029443	14029425	Accessing a non-static member via Lazy<T> or any lambda expression	private Lazy<int> lazyGetSum;\npublic MyClass()\n{\n   lazyGetSum = new Lazy<int>(new Func<int>(() => X + Y));\n}	0
14018154	14017992	Creating array of images based on user inputs	int numberOdRows=int32.Parse(NoRows.Text); //NoRows is the 1st textBlock\nint numberOdColumns=int32.Parse(NoCols.Text); //NoCols is the 2st textBlock\n\nStackPanel _stack0=new StackPanel { orientation = Orientation.Vertical};\nfor (int i=1;i<numberOdRows;i++)\n{\n    StackPanel _stack1=new StackPanel{ orientation = Orientation.Horizontal};\n    for (int j=1;i<numberOdColumns;i++)\n    {\n         image; //I assume you can call it\n        _stack1.Children.Add(image)\n\n        //here you can set the Tooltip too.\n        // i is the number of row\n        // j is the number of column\n        image.ToolTip="(" + i.ToString() + "," + j.ToString() + ")" ;\n    }\n    _stack0.Children.Add(_stack1)\n}\n\n//Add _stack0 to your panel	0
24727216	24727203	Get the sum of int values in a Dictionary<string, List<int>>()	teamScoreDict.ToDictionary(k => k.Key, v => v.Value.Sum())	0
17224208	17224188	Observing for changes in a List<>'s Count property?	ObservableCollection<T>	0
3117129	3117115	Link to the Device Manager	Process.Start("devmgmt.msc");	0
1418378	1418368	How does one select all text in a Windows Forms TextBox?	textbox.SelectAll();	0
3787036	3786984	Determine Declaring Order of Python/IronPython Functions	members = list(c.__dict__) # or c.__dict__.keys()	0
321678	263578	Report Viewer - Request for the permission of type SqlClientPermission failed	reportViewer.LocalReport.ExecuteReportInCurrentAppDomain(System.Reflection.Assembly.GetExecutingAssembly().Evidence);	0
