20203862	20201484	How can I replace an empty or null val with a default "base" value?	id = obj.Value<string>("Id") ?? "";\npackSize = obj.Value<short?>("PackSize") ?? (short)0;\nvar description = obj.Value<string>("Description") ?? "";\nvar deptSubdept = obj.Value<double?>("DeptDotSubdept") ?? 0.0;\nvar unitCost = obj.Value<double?>("Unit_Cost") ?? 0.0;\n...\nvar crvId = obj.Value<int>("CRV_Id") ?? 0;	0
25745828	25745657	What is self hosting ? Can it be used with webapi to communicate with devices?	var config = new HttpSelfHostConfiguration("http://localhost:8080");\n\nconfig.Routes.MapHttpRoute(\n    "API Default", "api/{controller}/{id}", \n    new { id = RouteParameter.Optional });\n\nusing (HttpSelfHostServer server = new HttpSelfHostServer(config))\n{\n    server.OpenAsync().Wait();\n    Console.WriteLine("Running on port 8080 - Press Enter to quit.");\n    Console.ReadLine();\n}	0
1665573	1664577	What is the best way to get a proper type name from a C# keyword?	private static Type GetTypeByFullNameOrAlias(string typeName)\n{\n  Type type = Type.GetType(typeName);\n\n  if (type == null)\n  {\n    using (var provider = new CSharpCodeProvider())\n    {\n      var compiler = provider.CompileAssemblyFromSource(\n        new CompilerParameters\n          {GenerateInMemory = true, GenerateExecutable = false, IncludeDebugInformation = false},\n        "public class A { public " + typeName + " B; }");\n\n      type = ((FieldInfo)compiler.CompiledAssembly.GetType("A").GetMember("B")[0]).FieldType;\n    }\n  }\n\n  return type;\n}	0
18954750	18949254	change cursor over a pictureBox	private void pictureBox1_MouseEnter(object sender, EventArgs e)\n    {\n        pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;\n        pictureBox1.Cursor = Cursors.Hand;\n    }\n\n    private void pictureBox1_MouseLeave(object sender, EventArgs e)\n    {\n        pictureBox1.SizeMode = PictureBoxSizeMode.Zoom;\n        pictureBox1.Cursor = Cursors.Default;\n    }	0
26267178	26265672	Get the combobox from data template in WPF DataGrid	FrameworkElement elmtTest = grdTest.Columns[7].GetCellContent(e.Row);\nComboBox myComboBox = FindVisualChild<ComboBox>(elmtTest);	0
6790133	6789960	Creating a file in Windows CE 5.0 in C#	private void saveFile()\n{\n    // If the File does not exist, create it!\n\n    if (! File.Exists("date.txt") ) // may have to specify path here!\n    {\n        // may have to specify path here!\n        File.Create("date.txt").Close();\n    }\n\n    // may have to specify path here!\n    StreamWriter swFile =\n                 new StreamWriter(\n                    new FileStream("date.txt",\n                                   FileMode.Truncate),\n                    Encoding.ASCII);\n\n    swFile.Write("some text");\n\n    swFile.Close();\n\n}	0
27819156	27819102	Find Number of Characters in a specific line in text file	var file = new StreamReader(@"D:\ValidFile.txt");\nstring line = null;\nint lineNumber = 0;\nwhile((line = file.ReadLine()) != null)\n{\n   Console.WriteLine("Line " + (lineNumber++) + ": " + line.Length);\n}	0
31842990	31842353	Accessing a text file in a WPF project	var uri = new Uri("pack://application:,,,/Subfolder/TextFile.txt");\nvar resourceStream = Application.GetResourceStream(uri);\n\nusing (var reader = new StreamReader(resourceStream.Stream))\n{\n    var text = reader.ReadToEnd();\n    ...\n}	0
16671473	16658713	How to notify about changing property of ListBox item?	var foundItem = shoppingList.FirstOrDefault(p => p.ean == item.ean);\n            if (foundItem != null)\n            {\n                foundItem.Amount += 1;\n                item.Amount = foundItem.Amount;\n            }	0
4095342	4095283	Custom Combining 4 dictionaries	var keys = dict1.Keys.Union(dict2.Keys).Union(dict3.Keys).Union(dict4.Keys);\nvar result = new Dictionary<string,List<string>>();\nforeach(var key in keys) {\n    List<string> list = new List<string>();\n    list.Add(dict1.ContainsKey(key) ? dict1[key] : "");\n    list.Add(dict2.ContainsKey(key) ? dict2[key] : "");\n    list.Add(dict3.ContainsKey(key) ? dict3[key] : "");\n    list.Add(dict4.ContainsKey(key) ? dict4[key] : "");\n    result.Add(key, list);\n}	0
3492857	3492840	Find the largest value smaller than x in a sorted array	int[] arr = { 1, 23, 57, 59, 120 };\nint index = Array.BinarySearch(arr, 109);\nif (index < 0)\n{\n    index = ~index - 1;\n}\nif (index >= 0)\n{\n    var result = arr[index];\n}	0
3688111	3688052	XML Doc - null handling	for (int i = 0; i < ds.Tables[0].Columns.Count; i++ )\n{\n    DataColumn col = ds.Tables[0].Columns[i] != null ? ds.Tables[0].Columns[i] : "<some default value>";\n    if (col != "<some default value>")\n                    // do something\n}	0
9335808	9335600	Is there a way to duplicate or make another copy of an XmlNodeList in C#?	var xd = new XmlDocument();\n    xd.LoadXml("<root><nodes><node>1</node><node>2</node></nodes></root>");\n    var xnl = xd.SelectSingleNode("/root/nodes").Clone();\n\n    foreach (XmlNode n in xnl)\n    {\n        n.InnerText = "x";\n    }\n\n    Console.Out.WriteLine(xd.OuterXml);\n    Console.Out.WriteLine("--------------");\n    Console.Out.WriteLine(xnl.OuterXml);	0
4772320	4772301	Removing \r from lines read from file	fileOutput.Replace("\r","")	0
27254929	27252327	Pass POST variables with Windows Phone App	using (var client = new HttpClient())\n            {\n                client.BaseAddress = new Uri("baseUrl.net");\n                var content = new FormUrlEncodedContent(new[]\n            {\n                new KeyValuePair<string, string>("Title", "test")\n            });\n\n                var result = await client.PostAsync("/insert.php", content);\n                string resultContent = "result: "+result.Content.ReadAsStringAsync().Result;	0
13729010	13728797	Custom Sort of ObservableCollection<T> with base type	var result = Children.OfType<ItemA>().OrderBy(a => a.ItemAName).Cast<Base>()\n    .Concat(Children.OfType<ItemB>().OrderBy(b => b.ItemBName));	0
23616058	23614893	SQL to LINQ Statement including Group By and Order By	var resultList = Table2\n            .Where(x => x.DateTime > begDate && x.DateTime < endDate)\n            .Join(Table1, t2 => t2.AccountId, t1 => t1.Id,\n                (t2, t1) => new { t2.AccountId, t1.Description })\n            .GroupBy(x => x.AccountId)\n            .Select(g => new { Group = g, Charges = g.Count() })\n            .OrderByDescending(g => g.Charges)\n            .SelectMany(g => g.Group.Select(x => new { x.Description, x.AccountId, g.Charges }))\n            .ToList();	0
21106756	21089792	Access Resource File Content in ASP.NET	var assembly = Assembly.GetExecutingAssembly();\nstring resourceName = (string)HttpContext.GetGlobalResourceObject("Resource1", "MyTemplate");\nstring mystring = "";\nmystring = resourceName;\nmystring = mystring.Replace("$$Member$$", name);\nmystring = mystring.Replace("$$Subject$$", TxtSubject.Text);\nreturn mystring;	0
16181659	16051922	Sending an Email asynchronously via ActionMailer	string url = baseUrl + "/api/Entry/SendEmail?emailId=" + emailId;\nWebRequest req = WebRequest.Create(url);\nreq.Method = "GET";\nreq.BeginGetResponse(null, null);	0
21864286	21863587	Button Click Event doesn't fire when clicking same button twice in a row	private void uxNumber_MouseDown(object sender, MouseButtonEventArgs e)\n{\n    if (e.LeftButton == MouseButtonState.Pressed)\n    {\n            int num = Convert.ToInt32(((GradientButton)sender).Text);\n\n        if (this.uxPIN.Text.Length < 4)\n            uxPIN.Text += num;    \n        else\n        SystemSounds.Beep.Play();\n    }\n\n}	0
19740448	19740406	c# - deserialization of specific JSON	var jsonValues = JsonConvert.DeserializeObject(someJsonString);\nvar pocoValue = JsonConvert.DeserializeObject<YourClass>(someJsonString);\n// or as a dictionary:\nvar dictionary = JsonConvert.DeserializeObject<Dictionary<MyClass>>(someJsonString);	0
15807703	15807191	C# How to get data into an array within an array	for (int j = 0; j < MAX_SONG; j++)\n            {\n                if (Songs[i] == null)\n                {\n                    index = i;\n                    break;\n                }\n            }	0
18758562	18757982	Windows Phone navigate to new instance of same page	NavigationService.Navigate(new Uri("/MainPage.xaml?ID="+ a.MyID, UriKind.Relative));\na.MyID++;	0
20966736	20966635	how to select values from listview column	private void button1_Click(object sender, EventArgs e)\n    {\n        int totalPrice = 0;\n        for(int i=0;i<listView1.Items.Count;i++)\n        {\n            totalPrice += Convert.ToInt32(listView1.Items[i].SubItems[2].Text);\n        }\n\n    }	0
10931763	10931642	How can I make sure a url provided by the user is not a local path?	new Uri(@"http://stackoverflow.com").IsLoopback\nnew Uri(@"http://localhost/").IsLoopback\nnew Uri(@"c:\windows\").IsLoopback	0
5572060	5571963	How to get DataGridView cell value in messagebox?	MessageBox.Show(dataGridView1.SelectedCells[0].Value.ToString());	0
2509314	2508930	Creating a custom TabPage control in C#	// form scoped variable to hold a referece to the current UserControl\n    private UserControl1 currentUserControl;\n\n    private void Form1_Load(object sender, EventArgs e)\n    {\n        foreach(TabPage theTabPage in tabControl1.TabPages)\n        {\n            currentUserControl = new UserControl1();\n\n            theTabPage.Margin = new Padding(0);\n            theTabPage.Padding = new Padding(0);\n\n            theTabPage.Controls.Add(currentUserControl);\n\n            currentUserControl.Location = new Point(0,0);\n\n            currentUserControl.Dock = DockStyle.Fill;\n\n            currentUserControl.SendToBack();\n        }\n    }	0
27537422	27537399	Exclude the number zero from modolus in an if statement	if ( r == 0){...}	0
11463800	11463734	Split a List into smaller lists of N size	public static List<List<float[]>> splitList(List <float[]> locations, int nSize=30)  \n{        \n    var list = new List<List<float[]>>(); \n\n    for (int i=0; i < locations.Count; i+= nSize) \n    { \n        list.Add(locations.GetRange(i, Math.Min(nSize, locations.Count - i))); \n    } \n\n    return list; \n}	0
16016230	16016065	Skipping compilation of a method depending on operating system or framework	#if CE\n ....\n#else\n ...\n#endif	0
6374002	6373908	How do you insert multiple records at once in LINQ to SQL while calling a sequence retrieval function on every insert	var db = new StoreDataContext();\nusing(var scope = new TransactionScope()){        \n    foreach(var p in payments){\n        db.payments.Insert(new payment \n                          {    order_fk = p.order_fk, \n                               line_no = DbMethods.GetNextLine(p.order_fk),     \n                                amount = p.amount\n                          });\n        db.SubmitChanges(ConflictMode.FailOnFirstConflict);\n    }\n    scope.Complete();\n}	0
27744943	27744901	How to get the index out from the string	var x = "FundList[10].Amount";\nint xIndex = Convert.ToInt32(Regex.Match(x,@"\d+").Value); //10	0
20004168	19929274	How to get Particular cell value from Previous row to Current Row in Gridview ?? Winforms Devexpress	object Value = MyGridView.GetRowCellValue("ColumnName", MyGridView.FocusedRowHandle - 1);	0
25143913	25143518	Temporary lock windows (re)size in WPF	this.ResizeMode = System.Windows.ResizeMode.NoResize;	0
13868223	13717189	Show series value over any point on chart using tooltip c#	private void chData_MouseMove(object sender, MouseEventArgs e)\n    {\n        try\n        {   \n            int cursorX = Convert.ToInt32(chData.ChartAreas[0].AxisX.PixelPositionToValue(e.Location.X));\n\n            tipInfo = "Bat 1: " + ch1Array[cursorX].ToString("0.00") + Environment.NewLine + "Bat 2: " + ch2Array[cursorX].ToString("0.00") + Environment.NewLine;\n\n            tooltip.SetToolTip(chData, tipInfo);\n\n        }\n        catch { }\n    }	0
11254725	11254609	Trying to get a string that represents a class heirachy	public class Class1 { }\n    public class Class2 : Class1 { }\n    public class Class3 : Class2 { }\n\n    private void button1_Click(object sender, EventArgs e)\n    {\n        Class3 c3 = new Class3();\n        Console.WriteLine(TypeToString(c3.GetType()));\n    }\n\n    private string TypeToString(Type t)\n    {\n        if (t == null)\n            return "";\n        if ((t.BaseType == null) || (t.BaseType == typeof(object)))\n            return t.Name;\n        return TypeToString(t.BaseType) + "." + t.Name;\n    }	0
2250506	2250490	Mark users coming to website from my application	string url = "http://mysite/somepage?source=myApplication";\nSystem.Diagnostics.Process.Start(url);	0
13645809	13645703	How search for HTML elements in StreamReader or String	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\ndoc.LoadHtml(htmlText);\n\nvar div = doc.DocumentNode.SelectSingleNode("//div[@id='bodyDiv']");\nif(div!=null)\n{\n    var yourtext = div.InnerText;\n}	0
17588908	17588713	How to add multiple bytes and get a byte array?	byte checksum;\nforeach (var b in someBytes)\n{\n    checksum = (byte)((checksum + b) & 0xff);\n}	0
685334	512553	Is there a way to measure the the amount of a string that will fit into a printed area without using the graphics object?	Size size = TextRenderer.MeasureString(this.Text, this.Font);	0
25131479	25131356	Entity Framework Eager load only a subset of other tables	var result = _context.Set<Document>()\n    .Where(d => d.IsActive)\n    .Select(d =>\n    new\n    {\n        Document = d,\n        Sections = d.Sections.Where(s => s.IsActive)\n    })\n    .ToArray().Select(anonymous => anonymous.Document).ToArray();	0
1896310	1896296	How to make sure a POST is requested from specific domain?	Request.ServerVariables["HTTP_REFERER"]	0
15584442	15584410	c# Set the value of combobox and texbox in the same foreach loop	var StringInput = new Control[] { preInput1, preInput5, postInput1, postInput5};\nint stringCount1 = 0;\nint toto = (ArrayCount + StringInput.Length);\n\nforeach (var c in StringInput)\n{\n  c.Text = Convert.ToString(energyCalculation.Cells[place[xCSV]].Value);\n  xCSV++;\n  //stringCount1++;\n  ArrayCount++;\n}	0
2456597	2456581	vs2003: identify first row in DataRow[]	bool isFirst = true;\n\nforeach(DataRow row in myrows)\n{\n    if (isFirst)\n    {\n        isFirst = false;\n        ...do this...\n    }\n    else\n    {\n        ....process other than first rows..\n    }\n}	0
26224255	26223870	Ordering entities based on other entity content	var query = conversations.OrderByDescending(c => c.Messages.Max(m => n.CreationDate))	0
10858268	10858103	Deserialize arbitrary JSON object with JSON.NET	yourString = yourString.Replace("\"list\":[]", "\"list\":{}");	0
925268	925034	Using SqlServer uniqueidentifier/updated date columns with Linq to Sql - Best Approach	partial void InsertTest(Test instance)\n{\n    instance.idCol = System.Guid.NewGuid();\n    this.ExecuteDynamicInsert(instance);\n}\n\npartial void UpdateTest(Test instance)\n{\n    instance.changeDate = DateTime.Now;\n    this.ExecuteDynamicUpdate(instance);\n}	0
27673262	27672628	How can i get value from SQL functions on c#	var con = new SqlConnection("Data Source=.;Initial Catalog=Project;Integrated Security=true;");\nvar cmd =new SqlCommand();\ncmd.Connection = con;\n\ncmd.CommandType = CommandType.Text;\ncmd.CommandText = "select dbo.[EnPahaliYemek](@yemekk);";    \ncmd.Parameters.AddWithValue("@yemekk", "whatever");\n\ncon.Open();\nlabel1.Text = cmd.ExecuteScalar().ToString();\ncon.Close();	0
19639760	19639577	Regex for substring between two known tags that might appear more than once	var match = Regex.Match(myStr, @"/([^/]+)\.stream\b");\nstring extracted = match.Groups[1].Value;\nConsole.WriteLine(extracted); // "unreachable"	0
1930206	1930196	What's the easiest way to generate a List<int> of ordered numbers in C#?	List<int> steporders = Enumerable.Range(1, 10).ToList();	0
13819213	13817300	Retrieve Xml attribute using XElement	var xml = @"<d:Answer xmlns:d=""http://www.test.com"" d:title=""abcd"">\n  <d:question id=""2.1"" answer=""test""  />\n  <d:question id=""2.2"" answer=""test""  />\n  <d:question id=""2.3"" answer=""Yes""  />\n</d:Answer>";\n\nXNamespace ns = "http://www.test.com";\nvar doc = XDocument.Parse(xml);\nvar question = doc.Descendants(ns + "question")\n                  .FirstOrDefault(x => (string)x.Attribute("id") == "2.1");	0
6672767	6670580	mapping multiple tables to a single entity class in entity framework	modelBuilder.Entity<TestResult>()\n    .Map(m =>\n      {\n        m.Properties(t => new { t.Name, t.Text, t.Units /*other props*/ });\n        m.ToTable("Result");\n      })\n    .Map(m =>\n      {\n        m.Properties(t => new { t.Status, t.Analysis /*other props*/});\n        m.ToTable("Test");\n      });	0
31003779	31001739	Modify Build process parameter by TFS API in C#	string argumentName = "TestDirectory";\nvar process = Microsoft.TeamFoundation.Build.Workflow.WorkflowHelpers.DeserializeProcessParameters(BuildDefinition.ProcessParameters);\n\nif (process.ContainsKey(argumentName))                             \n{\n    process.Remove(argumentName);\n    process.Add(argumentName, attributeValue);\n    BuildDefinition.ProcessParameters = WorkflowHelpers.SerializeProcessParameters(process);\n    BuildDefinition.Save();\n}	0
22777265	22777112	How generate chart from Excel sheet using c# interop?	// Add chart.\nvar charts = worksheet.ChartObjects() as\n    Microsoft.Office.Interop.Excel.ChartObjects;\nvar chartObject = charts.Add(60, 10, 300, 300) as\n    Microsoft.Office.Interop.Excel.ChartObject;\nvar chart = chartObject.Chart;\n\n// Set chart range.\nvar range = worksheet.get_Range(topLeft, bottomRight);\nchart.SetSourceData(range);\n\n// Set chart properties.\nchart.ChartType = Microsoft.Office.Interop.Excel.XlChartType.xlLine;\nchart.ChartWizard(Source: range,\n    Title: graphTitle,\n    CategoryTitle: xAxis,\n    ValueTitle: yAxis);	0
13524229	9110331	get i frame source using HtmlAgilityPack	HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument();\n\nHtmlNodeCollection nodes = doc.DocumentNode.SelectNodes("//iframe[@src]");\n\n\nforeach(var node in nodes){\n    HtmlAttribute attr = node.Attributes["src"];\n    Console.WriteLine(attr.Value);\n}	0
4095470	4095315	Other ways of 'disabling' a textbox against user input	TextBox1.Attributes.Add("readonly", "readonly")	0
16286653	16286581	Use nullable value if it HasValue	return number ?? 6;	0
32067441	32066761	How to allow null to be added to database	Cost = sectionGroup.Cost == null ? DBNull.Value : (double)sectionGroup.Cost	0
6836859	6836701	Remove current row from ObservableCollection	myCollection.Remove(Listbox1.Selecteditem)	0
32443083	32440235	Upload local image to deviantsart	var client = new RestClient("http://deviantsart.com");\nvar request = new RestRequest("upload.php", Method.POST);\nrequest.AddFile("pathtofileondisk.jpg");\n\nvar response = client.Execute(request);	0
10319799	10301838	Upload files to SQL from a csv	private void SaveFiles(List<string[]> files)\n     {\n        foreach (string[] attachment in files)\n        {\n            using (DataClasses1DataContext db = new DataClasses1DataContext())\n            {\n                string path = attachment[1].ToString();\n                byte[] fileBytes = File.ReadAllBytes(path);\n\n                ApplicantAttachment aa1 = new ApplicantAttachment();\n                aa1.Filename = attachment[0].ToString();\n                aa1.FileType = MIMEType.GetType(attachment[1].ToString());\n                aa1.Attachment = fileBytes;\n                db.ApplicantAttachments.InsertOnSubmit(aa1);\n                db.SubmitChanges();\n\n            }\n        }\n     }	0
11096830	11096546	How to change binary to string	string data = "0A0B0C0F1102"; // example data\nif (data.Length % 2 != 0) { data = "0" + data; } \n\nbyte[] result = new byte[data.Length / 2];\nfor (int i = 0; i < data.Length; i += 2) {\n    result[i/2] = Convert.ToByte(data.Substring(i, 2), 16);\n}\nBinary image = result;	0
28031064	28010788	how to set custom date format for specific column in datagridview? - c#	this.dataGridView1.Columns["YourDateCol"].DefaultCellStyle.Format = "dd/MM/yyyy";	0
15100023	15099952	How to fill a string with ordered elements via LINQ?	var equations = elements.Distinct().OrderBy(e => e.Id).Select(e => e.Equation);\nvar asString = string.Join(", ", equations);	0
1528886	1528508	Uncompress data file with DeflateStream	public static long Decompress(Stream inp, Stream outp)\n    {\n    byte[]  buf = new byte[BUF_SIZE];\n    long    nBytes = 0;  \n\n    // Decompress the contents of the input file\n    using (inp = new DeflateStream(inp, CompressionMode.Decompress))\n    {\n    int len;\n    while ((len = inp.Read(buf, 0, buf.Length)) > 0)\n    {\n    // Write the data block to the decompressed output stream\n    outp.Write(buf, 0, len);\n    nBytes += len;\n    }  \n    }\n    // Done\n    return nBytes;\n    }	0
5822312	5811241	using findcontrol for dropdownlist in a multiview	foreach (RepeaterItem item in edit_program.Items)\n{\n    var ddl = (DropDownList)item.FindControl("p_status");\n    ddl.Items.Add(new ListItem("Green", "Green"));\n}	0
7905224	7905100	Make a DataMember in a DataContract use implicit cast to string operator	[DataContract]\npublic class Root\n{\n    [DataMember]\n    public string MemberString { get{ return (string)this.Member; } set{this.Member=(Element)value;} }\n\n    public Element Member { get; set; }\n}	0
7438120	7437952	Map string column in Entity Framework to Enum	public virtual string StatusString\n{\n    get { return Status.ToString(); }\n    set { OrderStatus newValue; \n          if (Enum.TryParse(value, out newValue))\n          { Status = newValue; }\n        }\n}\n\npublic virtual OrderStatus Status { get; set; }	0
29354109	29354074	Multi-Dimensional Array - Array of arrays?	string[][]	0
23424849	23421267	How to get and set text editor value in selenium	IJavaScriptExecutor js = (IJavaScriptExecutor)driver;\n        js.ExecuteScript("document.getElementsByClassName('cke_wysiwyg_frame')[0].contentDocument.getElementsByClassName('cke_editable_themed')[0].innerHTML='dfjkbgdk';");	0
12979381	12978894	Change Windows 7 app taskbar icon color	// This will highlight the icon in red\nTaskbarManager.Instance.SetProgressState(TaskbarProgressBarState.Error);\n// to highlight the entire icon\nTaskbarManager.Instance.SetProgressValue(100,100);	0
7675117	7674955	Found minimum and maximum value from dataset containing multiple tables	int minAccountLevel = int.MaxValue;\nint maxAccountLevel = int.MinValue;\n\nfor (int i = 0; i < 3; i++)\n{\nvar table = ds.Tables[i];\nforeach (DataRow dr in table.Rows)\n{\n    int accountLevel = dr.Field<int>("AccountLevel");\n    minAccountLevel = Math.Min(minAccountLevel, accountLevel);\n    maxAccountLevel = Math.Max(maxAccountLevel, accountLevel);\n}\n}	0
5128437	5128421	How to stop the execution and make a redirect to the login page	FormsAuthentication.SignOut();\nResponse.Redirect("URLToLoginPage");	0
20858332	20848815	WP8/XAML - Measure string length in pixels	public int TextWidth(string text)\n    {\n        TextBlock t = new TextBlock();\n        t.Text = text;\n        //Height and Width are depending on font settings\n        //t.FontFaimily=...\n        //t.FontSize=...\n        //etc.\n        return (int)Math.Ceiling(t.ActualWidth);\n    }	0
226775	226572	XPath in C# code behind of WPF	XPathDocument doc = new XPathDocument(@"c:\filepath\doc.xml");\nXPathNavigator nav = doc.CreateNavigator();\nXPathNodeIterator iter = nav.Select("/xpath/query/here");\n\nwhile(iter->MoveNext)\n{\n  //Do something with node here.\n}	0
9916576	9915160	How to display text in a WPF GridView that contains carriage returns	public string TextBlockText { get { return "one line \r\ntwo line"; } }\n\n <TextBlock Height="Auto" Width="100" HorizontalAlignment="Left" Text="{Binding Path=TextBlockText}" />	0
7460174	7460129	ASP.NET SqlDataSource parameter declaration in code behind	sqlDataSource.SelectParameters.Add(new Parameter("One", System.TypeCode.Int32, recordNo))	0
7981396	7981301	Generate white noise image in C#	foreach(var pixel in image)\n{\n    pixel = rand()>0.5 ? white : black;\n}	0
8439773	8439757	how to run batch queries in sql ce?	SqlCeCommand oCommand = conn.CreateCommand();\noCommand.CommandText = "insert into contacts(name, emails) values(?, ?)";\n// I can't remember if the param names need @ or not\noCommand.Parameters.Add("@name", SqlDbType.VarChar);\noCommand.Parameters.Add("@email", SqlDbType.VarChar);\n\nSqlCeTransaction oTrans = conn.BeginTransaction();\ntry {\n  foreach (KeyValuePair<string, string> key in list) {\n     oCommand.Parameters[0].Value = key.Key;\n     oCommand.Parameters[1].Value = key.Value;\n     oCommand.ExecuteNonQuery();\n  }\n  oTrans.Commit();\n} catch (Exception ex) {\n  oTrans.Rollback();\n}	0
9017567	9017498	Calculating how many minutes there are between two times	DateTime startTime = varValue\n\nDateTime endTime = varTime\n\nTimeSpan span = endTime.Subtract ( startTime );\nConsole.WriteLine( "Time Difference (seconds): " + span.Seconds );\nConsole.WriteLine( "Time Difference (minutes): " + span.Minutes );\nConsole.WriteLine( "Time Difference (hours): " + span.Hours );\nConsole.WriteLine( "Time Difference (days): " + span.Days );	0
3208634	3208573	How to specify pattern that should not match	var input = "Hello";\nvar regEx = new Regex("World");\nreturn !regEx.IsMatch(input);	0
24150915	24150675	Search substring in text file	int theNumber;\nstring[] lines = System.IO.File.ReadAllLines("c:\\the file.txt");\nfor( int i = 0; i < lines.Length; i++ )\n{\n    if( lines[i].Contains( "Total no. of objects processed successfully" ) )\n    {\n        theNumber = Convert.ToInt32( lines[i].Substring( lines[i].LastIndexOf('-') + 2 ) );\n    }\n}	0
7014763	7014393	Manipulate XML XDocument XmlDocument C#	var doc = XDocument.Load(...);\nXNamespace envNs = "http://schemas.xmlsoap.org/soap/envelope/";\nvar fromUri = doc.Root\n       .Element(envNs + "Header")\n       .Element("Authorization")\n       .Element("FromURI");\nfromUri.Value = "http://trst";\ndoc.Save(...);	0
25955118	25942733	Abort reading from serial to start writing?	int datalen = serialPort1.BytesToRead;\nlabel1.Text="Readexisting";\nif (datalen >=10)\n{\n    string data = serialPort1.ReadExisting();\n    label1.Text=data;\n}	0
23715473	23715423	c# compare two numbers got from two files	void CompareVersions()\n{\n    WebClient client = new WebClient();\n    var serverVersion = client.DownloadString("http://yourwebsite.com/version.txt");\n\n    using (StreamReader sr = new StreamReader("file.txt"))\n    {\n        if (Convert.ToInt32(serverVersion) > Convert.ToInt32(sr.ReadLine()))\n        {\n            // server version bigger\n        }\n        else\n        {\n            // up to date\n        }\n    }\n}	0
31605385	31605293	Designing interface for tree-like structure	public interface ITreeNode<T> where T : ITreeNode<T>\n{\n    T ParentNode { get; set; }\n    ICollection<T> ChildNodes { get; set; }\n}\n\npublic class FooNode : ITreeNode<FooNode>\n{\n    public FooNode ParentNode { get; set; }\n    public ICollection<FooNode> ChildNodes { get; set; }\n}	0
20375746	20375582	How can I add a attribute to Root node of my XmlDocument() in C#	document.DocumentElement.Attributes.Append(document.CreateAttribute("uuid")).Value = "12345"	0
30080759	30080678	How to find a right click event on MouseUp anywhere on the form?	this.MouseUp += new MouseEventHandler(this.form_MouseUpToGetHelpText);\n\n\nprivate void form_MouseUpToGetHelpText(object sender, MouseEventArgs e)\n{\n  if (e.Button == System.Windows.Forms.MouseButtons.Right)\n  {\n      // Logic here\n  }\n}	0
30791519	30791255	How to give a child window bounds to not go outside the MainWindow in WPF	public MainWindow()\n  {\n   InitializeComponent();     \n   LocationChanged += new EventHandler(Window_LocationChanged);\n  }\n\n\nChildWindow win = new ChildWindow();\n   win.Owner = this;\n   win.Show();\n\nprivate void Window_LocationChanged(object sender, EventArgs e)\n  {\n   Console.WriteLine("LocationChanged - ({0},{1})", this.Top, this.Left);\n   foreach (Window win in this.OwnedWindows)\n   {\n    win.Top = this.Top + 100;\n    win.Left = this.Left + 100;\n   }\n  }	0
10034778	10034715	Using a method with generic parameters as a callback	public class SomeClass<TParam, TReturn>\n{\n    private Func<TParam, TReturn> _callback;\n\n    public class SomeClass(Func<TParam, TReturn> callback)\n    {\n        _callback = callback;\n    }\n}	0
11042833	11042688	WPF Binding a List to a DataGrid	public List<ComputerRecord> GridInventory\n{\n    get { return _gridInventory; }\n    set \n    { _gridInventory = value; \n      RaisePropertyChanged("GridInventory");\n    }\n}	0
20326887	20324977	how to get the distinct item from listview in windows application	// take only the last character which is a letter (A, B, ...)\nvar letterList = list.Select(i => i.Last());\n// group the letters and select those which are present more than once\nvar dups = letterList.GroupBy(i => i)\n                     .Where(i => i.Count() > 1)\n                     .Select(i => i.Key);\n// take the resulting letter and join them with the ',' character\nvar result = string.Join(",", dups); // or textBox.Text = ...	0
14878913	14878871	Design: List storing objects; access information associated with that object	theList.Where(x => x.address == "999 Candy Lane").First();	0
17963159	17963117	How to fill a region with transparency in windows forms application	Color.FromArgb(0...255, r, g, b)	0
14567081	14566376	How save photo capture windows 8 c# metro app?	FileSavePicker savePicker = new FileSavePicker();\n  savePicker.SuggestedStartLocation = PickerLocationId.PicturesLibrary;\n  savePicker.FileTypeChoices.Add("jpeg image", new List<string>() { ".jpeg" });\n  savePicker.SuggestedFileName = "New picture";\n\n  StorageFile ff = await savePicker.PickSaveFileAsync();\n  if (ff != null)\n  {\n    await photo.MoveAndReplaceAsync(ff);\n  }	0
25117000	25116943	Printing the Given numbers in given columns and rows Console Application	string total, rows, columns = "";\n\ntotal = "30";\nvar allNumbers = "1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30";\nvar array = allNumbers.Split(',');\n\nrows = "5";\n\ncolumns = "6";\n\nfor (int i = 0; i < Convert.ToInt32(rows); i++)\n{\n    for (int j = 0; j < Convert.ToInt32(columns); j++)\n    {\n        Console.Write(array[j + (i * Convert.ToInt32(columns))]);\n        Console.Write("\t");\n    }\n\n    Console.WriteLine();\n}	0
25405255	25402496	API or Library to process vCalendar information?	DateTime localTime = DateTime.SpecifyKind(DateTime.Parse(strDate),  \n                                          DateTimeKind.UTC).ToLocalTime();	0
12054258	12049425	Add caption to access fields with c#	using Microsoft.Office.Interop.Access.Dao;\n\n\n        DBEngine dbEng = new DBEngine();\n        Workspace ws = dbEng.CreateWorkspace("", "admin", "",\n            WorkspaceTypeEnum.dbUseJet);\n        Database db = ws.OpenDatabase(@"z:\docs\test.accdb", false, false, "");\n        TableDef tdf = db.TableDefs["Table1"];\n        Field fld = tdf.Fields["Field1"];\n\n        Property prp = fld.CreateProperty("Caption", 10, "My caption");\n\n        fld.Properties.Append(prp);	0
1786778	1786695	linq return single row from a goup	var query = yourData\n            .GroupBy(x => new { x.Vol, x.Component, x.Dwg, x.View })\n            .Select(g => g.OrderByDescending(x => x.Revision).First());\n\n// and to test...\nforeach (var x in query)\n{\n    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}",\n        x.Vol, x.Component, x.Dwg, x.View, x.Revision ?? "NULL");\n}\n\n// Volume U01    Composed Drawings    SJTest     1    B\n// Volume U03    Composed Drawings    SJTest2    2    NULL	0
5928173	5925069	Save Icon File To Hard Drive	string s = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + @"\IconData.ico";\n        using (FileStream fs = new FileStream(s, FileMode.Create))\n            ico.Save(fs);	0
